Anagram using PHP array

Finding the number of anagram words in given string.

Did you have a question?

Yes, I am stuck with that anagram words using PHP.

suppose you have string as “mum mmu ppo pop xyz zyx bb bb”;
Need to find the agagram words from the string. so it should give me answer as 3 . Should not consider “bb” as it is same word and not considered as anagram.

1 Like

Hi @kishor.koshti!

Welcome to the forum!

You will get more responses if you share with the forum what you have tried.

Please share your code if you would like to receive assistance.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Hi @kishor.koshti here are two ways

  1. easy way would be to use inbuilt functionality already in php, here is a script i wrote for you:
function agram($arr)
    echo "<br/>";
    $count = 0;
    $n = count($arr);
    for ($i = 0; $i < $n - 1; $i++) {
        for ($j = $i + 1; $j < $n; $j++) {
            if (count_chars($arr[$i], 1) == count_chars($arr[$j], 1)) {
                echo $arr[$i] . " " . $i . "i equals j" . $j . " " . $arr[$j] . "<br/>";
            } else {
                echo $arr[$i] . " " . $i . "i does not equal j" . $j . " " . $arr[$j] . "<br/>";

    echo $count;

$str = "mum mmu ppo pop xyz zyx bb bb";
$uniqueArr = array_unique(explode(" ", $str));
  1. Harder way, do not rely on inbuilt functionality of language, use data structure like in this challenge here (Trie):

Hope this helps