0

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;  

}

3 Answers3

3

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
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
  • 1
    I did, the add some code at the bottom for testing to see if you pass.. they trow a series of test cases in and the error code is showing that their line of code is not working now... so its them... not your code. – Shout It Web Solutions Oct 29 '14 at 04:37
  • I'm solving all their question for interview i'm having and all sort function are not working even usort – Bakly Dec 19 '14 at 20:54
1

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

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

See demo

Mark Miller
  • 7,442
  • 2
  • 16
  • 22
  • so there is no function like sort() that will return either a string or an array? – Shout It Web Solutions Oct 29 '14 at 04:25
  • @ShoutItWebSolutions `sort()` sorts the given array. In your case, why would you need to create another array, when you can just use `sort` to sort the one you have? If you wanted, you could create a copy of the array and then sort that... `$arr2 = $arr; sort($arr2); ...` but why would you need to...? – Mark Miller Oct 29 '14 at 04:28
  • 1
    @ShoutItWebSolutions try this solution most likely this will work just fine, `sort()` works on arrays, `str_split` just turned your input string into an array so that `sort()` could manage to sort it alphabetically. the `implode()` just glued up the sorted array back into a string again. – Kevin Oct 29 '14 at 04:29
  • that was my logic... except I misunderstood the output of sort() i though it returned an array. – Shout It Web Solutions Oct 29 '14 at 04:35
0

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);
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87