Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which case PHP sort function returns FALSE?

Tags:

php

sorting

PHP sort() function and other functions from this family returns true on success or false on failure. In which case sort function returns false? What is possible source of failure?

Example:

$array = [1, 5, 22, 8, 3, 3];
$returnValue = sort($array);
var_dump($returnValue);   // bool(true)

I can't imagine any case in which $returnValue could be false.

I have also tried sort variants with user-defined comparison function, which can possibly introduce some error, but with no success.

$array = [1, 5, 22, 8, 3, 3];
$returnValue = usort($array, function($a, $b) { return 'Hello World'; });
var_dump($returnValue);   // bool(true)

Actually you can do whatever you want in your comparison function, because callback's return value is internally casted to integer, and you will get $returnValue === true everytime. This also applies for user-defined comparison function without returned value. PHP returns null in this case, which is internally casted to integer: (int)null === 0 and thus everything is correct.

like image 982
Lukas Hajdu Avatar asked Mar 21 '15 09:03

Lukas Hajdu


People also ask

What does sort return in PHP?

Return Value: It returns a boolean value, TRUE on success and False in failure. It sorts the original array in ascending order which is passed as a parameter.

What is the use of sort () function in PHP?

Definition and Usage The sort() function sorts an indexed array in ascending order. Tip: Use the rsort() function to sort an indexed array in descending order.

Which of the following is a PHP function for sorting arrays?

PHP - Sort Functions For Arrayssort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.


1 Answers

It will return false if parameter one is not an array

like image 94
Richard Turner Avatar answered Sep 21 '22 03:09

Richard Turner