Using PHP write an anagram function?

14,799

Solution 1

There's simpler way

function is_anagram($a, $b) {
    return(count_chars($a, 1) == count_chars($b, 1));
}

example:

$a = 'argentino';
$b = 'ignorante';
echo is_anagram($a,$b);   // output: 1

$a = 'batman';
$b = 'barman';
echo is_anagram($a,$b);  // output (empty):

Solution 2

function is_anagram($pharse1,$pharse2){
  $status = false;
  if($pharse1 && $pharse2){
   $pharse1=strtolower(str_replace(" ","", $pharse1));
   $pharse2=strtolower(str_replace(" ","", $pharse2));
   $pharse1 = str_split($pharse1);
   $pharse2 = str_split($pharse2);
   sort($pharse1);
   sort($pharse2);
   if($pharse1 === $pharse2){
   $status = true;
   } 
  }
  return $status;
}

Solution 3

here is my variant :

public function is_anagram($wrd_1, $wrd_2) 
  {
  $wrd_1 = str_split ( strtolower ( utf8_encode($wrd_1) ) );
  $wrd_2 = str_split( strtolower ( utf8_encode($wrd_2) ) );

  if ( count($wrd_1)!= count($wrd_2) ) return false;
  if ( count( array_diff ( $wrd_1 ,$wrd_2) ) > 0 ) return false;

  return true;
  }

Solution 4

 function check_anagram($str1, $str2) {
      if (count_chars($str1, 1) == count_chars($str2, 1)) {
           return "This '" . $str1 . "', '" . $str2 . "' are Anagram";
      }
      else {
          return "This two strings are not anagram";
      }

  }
    ECHO check_anagram('education', 'ducatione');

Solution 5

I don't see any answers which have addressed the fact that capital letters are different characters than lowercase to count_chars()

if (isAnagram('Polo','pool')) {
    print "Is anagram";
} else {
    print "This is not an anagram";
}

function isAnagram($string1, $string2)
{
    // quick check, eliminate obvious mismatches quickly
    if (strlen($string1) != strlen($string2)) {
        return false;
    }

    // Handle uppercase to lowercase comparisons
    $array1 = count_chars(strtolower($string1));
    $array2 = count_chars(strtolower($string2));

    // Check if 
    if (!empty(array_diff_assoc($array2, $array1))) {
        return false;
    } 
    if (!empty(array_diff_assoc($array1, $array2))) {
        return false;
    } 

    return true;
}
Share:
14,799
Vijay
Author by

Vijay

Updated on June 14, 2022

Comments

  • Vijay
    Vijay almost 2 years

    Using PHP write an anagram function? It should be handling different phrases and return boolean result.

    Usage:

    $pharse1 = 'ball';
    $pharse2 = 'lbal';
    if(is_anagram($pharse1,$pharse2)){
      echo $pharse1 .' & '. $pharse2 . ' are anagram';
    }else{
      echo $pharse1 .' & '. $pharse2 . ' not anagram';
    }