Stora a sorted array in a new variable


#1

Hi, why doesn't this work:

$fruits = array("banana", "apple", "orange");
$sortedFruits = sort($fruits);
echo join(", ", $sortedFruits);

I would be glad to hear your respons! :slightly_smiling:


#2

sort() returns a bool value of either true or false. So when you assign it to $sortedFruits, you don't get an array but single element with value of 0 or 1.

$fruits = array("banana", "apple", "orange");
sort($fruits);
$sortedFruits = $fruits;
echo join(", ", $sortedFruits);

The solution is to sort the $fruits array first, and assign it to $sortedFruits later, or assign it first and then sort the new array. Another option would be this

$fruits = array("banana", "apple", "orange");
sort($fruits);
echo join(", ", $fruits);

You can use that if you don't have to save the value of sorted field to a new variable.


#3

Ok, thats why! Thank you so much for your reply! :slightly_smiling:


#4

You're welcome. If you are ever unsure about what and why is returned as a value, you can always consult PHPnet.
Here is the link to sort function. You can search all PHP functions there, and even view some examples in comments.


#5

Thanks, I will check PHP.net!