php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #51835 Example cmp() in uasort() documentation is incorrect
Submitted: 2010-05-16 22:40 UTC Modified: 2010-05-17 20:44 UTC
From: dave+php at davereid dot net Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: Irrelevant OS: Ubuntu/9.10
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: dave+php at davereid dot net
New email:
PHP Version: OS:

 

 [2010-05-16 22:40 UTC] 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
)
?>

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-05-17 20:44 UTC] bjori@php.net
-Status: Open +Status: Bogus
 [2010-05-17 20:44 UTC] bjori@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon May 27 21:01:33 2024 UTC