Doc #51835 [Opn->Bgs]: Example cmp() in uasort() documentation is incorrect

From: Date: Mon, 17 May 2010 18:44:59 +0000
Subject: Doc #51835 [Opn->Bgs]: Example cmp() in uasort() documentation is incorrect
References: 1  Groups: php.doc.bugs 
Request: Send a blank email to doc-bugs+get-4392@lists.php.net to get a copy of this message
Edit report at http://bugs.php.net/bug.php?id=51835&edit=1 ID: 51835 Updated by: bjori@php.net Reported by: dave+php at davereid dot net Summary: Example cmp() in uasort() documentation is incorrect -Status: Open +Status: Bogus Type: Documentation Problem Package: Documentation problem Operating System: Ubuntu/9.10 PHP Version: Irrelevant New Comment: Thank you for taking the time to write to us, but this is not a bug. Please double-check the documentation available at http://www.php.net/manual/ and the instructions on how to report a bug at http://bugs.php.net/how-to-report.php When two values are equal then return -1 or 1 is bogus. -1 means $a is less then $b +1 means $a is greater then $b 0 means $a equals to $b Its perfectly valid to have to equal values, in which case you return 0. However. Weather or not equal values will be swapped or not is undefined. Usually you don't care if the values are swapped or not. If you care, then return a different value. Previous Comments: ------------------------------------------------------------------------ [2010-05-16 22:40:21] dave+php at davereid dot net Description: ------------ The sorting function used in the example of uasort() is incorrect because it will cause elements with equal values to still be swapped. Sorting functions should never return a value of 0. It should always be either -1 or 1. Test script: --------------- This is the exact sorting example from http://php.net/manual/en/function.uasort.php: <?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); ?> Expected result: ---------------- To not have the 'c' and 'd' elements swapped. <?php Array ( [a] => 4 [b] => 8 [c] => -1 [d] => -1 ) Array ( [c] => -1 [d] => -1 [a] => 4 [b] => 8 ) ?> Actual result: -------------- The 'c' and 'd' elements are swapped, even though they had the same values. <?php Array ( [a] => 4 [b] => 8 [c] => -1 [d] => -1 ) Array ( [d] => -1 [c] => -1 [a] => 4 [b] => 8 ) ?> ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/bug.php?id=51835&edit=1

« previous php.doc.bugs (#4392) next »