简体   繁体   中英

Sort string into alphabetical order

I'm working through the challenges on coderbyte.com to brush up on programming skills. The challenge is to sort a string $str into alphabetical order. The output must be a string, I'm 99% my logic and code is correct but its throwing errors, Can anyone spot if I have done anything wrong before I contact coderbyte.

eg if $str = cat hat; $imp should return 'aacht' my code is:

function AlphabetSoup($str) {  


 $arr = str_split($str, 1);
 $sorted = sort($arr);
 $imp = implode('', $sorted);


  return $imp;  

}

sort() returns true or false, not an array. Try this:

...
$arr = str_split($str, 1);
sort($arr);
$imp = implode('', $arr);
...

See demo

sort() :- Returns TRUE on success or FALSE on failure.
You need to quoting over string like $str = 'cat hat'; and you will get result Try

$str = 'cat hat';
$sparts = str_split($str);
sort($sparts);
$imp = implode('', $sparts); //aachtt 
return $imp;  // will be a string

sort() returns TRUE on success or FALSE on failure. so $sorted would contain boolean value not an array .It will sort the array. try with -

$arr = str_split($str, 1);
sort($arr);
$imp = implode('', $arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM