note 97932 added to function.uasort
| From: | dave+php at davereid dot net | Date: | Sun, 16 May 2010 20:53:32 +0000 |
| Subject: | note 97932 added to function.uasort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-169310@lists.php.net to get a copy of this message | ||
Note that your sort function should *never* return a value of 0 because it will still cause two
items of 'equal' value to be swapped.
Using the cmp() function in the documentation with two keys that have the same values:
<?php
// Comparison function
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd'
=> -1);
print_r($array);
// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>
Results in the elements with keys 'c' and 'd' being swapped around:
<?php
Array
(
[a] => 4
[b] => 8
[c] => -1
[d] => -1
)
Array
(
[d] => -1
[c] => -1
[a] => 4
[b] => 8
)
?>
If you remove the return '0' condition in cmp(), you get what everyone would expect, that
'c' and 'd' have not been swapped.
<?php
Array
(
[a] => 4
[b] => 8
[c] => -1
[d] => -1
)
Array
(
[c] => -1
[d] => -1
[a] => 4
[b] => 8
)
?>
----
Server IP: 69.147.83.197
Probable Submitter: 98.161.6.254
----
Manual Page -- http://www.php.net/manual/en/function.uasort.php
Edit -- https://master.php.net/note/edit/97932
Del: integrated -- https://master.php.net/note/delete/97932/integrated
Del: useless -- https://master.php.net/note/delete/97932/useless
Del: bad code -- https://master.php.net/note/delete/97932/bad+code
Del: spam -- https://master.php.net/note/delete/97932/spam
Del: non-english -- https://master.php.net/note/delete/97932/non-english
Del: in docs -- https://master.php.net/note/delete/97932/in+docs
Del: other reasons-- https://master.php.net/note/delete/97932
Reject -- https://master.php.net/note/reject/97932
Search -- https://master.php.net/manage/user-notes.php