Reputation: 161
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;
}
Upvotes: 1
Views: 1321
Reputation: 17805
You have almost done it. Not really sure if count of spaces also matter, but for now, I presume it does.
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)));
Upvotes: 2