Created
December 12, 2016 07:55
-
-
Save sphinxid/419ed2db474d9728a31991e236fc83dc to your computer and use it in GitHub Desktop.
Simple anagram checker in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* 2016/12/12 | |
* | |
* anagram.php | |
* Simple anagram checker. (cAsE sEnsiTivE) | |
* | |
* Firman Gautama <[email protected]> | |
* | |
*/ | |
$str1 = "abcabc123"; | |
$str2 = "cbabca321"; | |
$check = isAnagram($str1, $str2); | |
printf("String '%s' and '%s' is %s.\n", $str1, $str2, ($check ? "Anagram" : "Is Not Anagram")); | |
function isAnagram(&$str1, &$str2) { | |
// check if both string have the same length. | |
if (strlen($str1) !== strlen($str2)) { | |
return false; | |
} | |
$t_s1 = Array(); | |
$t_s2 = Array(); | |
$len = strlen($str1); | |
for ($i=0;$i<$len;$i++) { | |
// map str1 character count | |
if (empty($t_s1[$str1{$i}])) { | |
$t_s1[$str1{$i}] = 1; | |
} | |
else { | |
$t_s1[$str1{$i}]++; | |
} | |
// map str2 character count | |
if (empty($t_s2[$str2{$i}])) { | |
$t_s2[$str2{$i}] = 1; | |
} | |
else { | |
$t_s2[$str2{$i}]++; | |
} | |
} | |
// debug | |
//print_r($t_s1); | |
//print_r($t_s2); | |
// if the character count is not same, that's mean the string is not anagram | |
foreach ($t_s1 as $k => &$v) { | |
if ($t_s1[$k] !== $t_s2[$k]) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment