note 97932 deleted from function.uasort by degeberg

From: Date: Sun, 16 May 2010 21:16:39 +0000
Subject: note 97932 deleted from function.uasort by degeberg
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169311@lists.php.net to get a copy of this message
Note Submitter: dave+php at davereid dot net ---- 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 ) ?>

« previous php.notes (#169311) next »