pastebin

Paste Search Dynamic
Recent pastes
is_anagram
  1. <?php
  2.  
  3. function is_anagram($s1, $s2){
  4. //Removing all white spaces from s1 and s2
  5. $copyOfs1 = str_replace(' ', '', $s1);
  6. $copyOfs2 = str_replace(' ', '', $s2);
  7.  
  8. //Initially setting status as true
  9. $status = true;
  10.  
  11.     if(strlen($copyOfs1) != strlen($copyOfs2)){
  12.         //Setting status as false if copyOfs1 and copyOfs2 doesn't have same length  
  13.         $status = false;
  14.     }else{
  15.         //Changing the case of characters of both copyOfs1 and copyOfs2
  16.         $str_to_lower_s1 = strtolower($copyOfs1);
  17.         $str_to_lower_s2 = strtolower($copyOfs2);
  18.  
  19.         //and converting them to array
  20.         $array_s1 = str_split($str_to_lower_s1);
  21.         $array_s2 = str_split($str_to_lower_s2);
  22.        
  23.         //Sorting both s1Array and s2Array
  24.         $sort_s1 = sort($array_s1);
  25.         $sort_s2  = sort($array_s2);
  26.  
  27.         //Checking whether s1Array and s2Array are equal
  28.         if($sort_s1 === $sort_s2){
  29.             $status = true;
  30.         }
  31.     }
  32.     //Output
  33.  
  34.     if($status){
  35.         echo $s1."  and ". $s2." are anagrams";
  36.     }else{
  37.         echo $s1."  and ". $s2." are not anagrams";
  38.     }
  39. }
  40.  
  41. // Driver code
  42. print_r(is_anagram('Dormitory', 'Dirtyroom')."<br>");
  43. print_r(is_anagram('Listen', 'Silent')."<br>");
  44. print_r(is_anagram('Mother In Law', 'Hitler Woman')."<br>");
  45. print_r(is_anagram('keEp', 'peeK')."<br>");
  46. print_r(is_anagram('SiLeNt CAT', 'LisTen AcT')."<br>");
  47. print_r(is_anagram('Debit Card', 'Bad Credit')."<br>");
  48. print_r(is_anagram('School MASTER', 'The ClassROOM')."<br>");
  49. print_r(is_anagram('ASTRONOMERS', 'NO MORE STARS')."<br>");
  50. print_r(is_anagram('Toss', 'Shot')."<br>");
  51. print_r(is_anagram('joy', 'enjoy')."<br>");
  52.  
  53.  
  54. ?>
Parsed in 0.060 seconds