Skip to content
Advertisement

Find all anagrams of a string in a given list of strings

I recently begun learning data structures and algorithm and I have this question I have been struggling with in PHP. I was able to implement it with Python but I am struggling to do the same with PHP. Any help would be appreciated.

*Given an array of strings, group anagrams together.
array(‘ate’, ”map’, ‘eat’, ”pat’, ‘tea’ , ‘tap’) * Below is my what I have done so far:

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;
}

Advertisement

Answer

You have almost done it. Not really sure if count of spaces also matter, but for now, I presume it does.

  • So split the string to get an array of individual characters.
  • Sort them in ascending/non-decreasing order.
  • Implode it back to get it as a sorted string.
  • As you already did starting 2 steps, now you just have to put the current string in an array where sorted key is the actual key where the current anagram belongs. See code for more clarity.

Snippet:

<?php

$map = [];

$data = array('ate', 'map', 'eat', 'pat', 'tea' , 'tap');

foreach($data as $str){
    $strSplit = str_split($str);
    sort($strSplit);
    $strSplit = implode("",$strSplit);
    $map[$strSplit][] = $str; 
}

print_r($map);

Update:

Looking at your output format, you can just do the below in the end to echo them together:

echo implode(" ",array_merge(...array_values($map)));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement