0

For example we have the following words: hey, hello, wrong

$unsorted = array("eyh", "lhleo", "nrwgo");

I know that I could use asort to sort the array alphabetically, but I don't want that. I wish to take the elements of the array and sort those, so that it would become something like this:

$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted

hey sorted = ehy

hello sorted = ehllo

wrong sorted = gnorw

As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.

Thanks in advance!

Mark
  • 8,046
  • 15
  • 48
  • 78
Ninjex
  • 1

3 Answers3

1
$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
     $myArray,
     function (&$value) {
         $value = str_split($value);
         sort($value);
         $value = implode($value);
     }
);
print_r($myArray);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • For those who complain that closures don't work in PHP 5.2, upgrade! PHP 5.2 is very old now, and no longer supported; even PHP 5.3 is no longer supported. PHP 5.5.1 is the current version, and PHP 5.2 is officially 2 years past its end-of-life date – Mark Baker Jul 23 '13 at 08:09
1
function sort_each($arr) {
    foreach ($arr as &$string) {
        $stringParts = str_split($string);
        sort($stringParts);
        $string = implode('', $stringParts);
    }
    return $arr;
}

$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )
BadgerPriest
  • 723
  • 5
  • 11
0

Try this

$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString =  implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);
nvn
  • 52
  • 3