Search code examples
arraysphpphp-internals

PHP uksort function using global variable fails after PHP upgrade to 5.3.3


I have a user defined sort function which uses a 'global' declaration in order to refer to a multi-dimensional array when deciding on the correct sort order. It used to work fine under PHP 5.1.6 but now fails under 5.3.3.

The code throws PHP warning:

PHP Warning: uksort(): Array was modified by the user comparison function

But the code definitely does not modify the array.

This code duplicates the problem:

$arr = array();

$arr['i1']['val1'] = 99;
$arr['i1']['val2'] = 100;

$arr['i2']['val1'] = 89;
$arr['i2']['val2'] = 101;


function cmp($a, $b)
{
    global $arr;

    if ($arr[$a]['val2'] > $arr[$b]['val2']) { return 1; }
    if ($arr[$a]['val2'] < $arr[$b]['val2']) { return -1; }
    return 0;
}

if (uksort($arr, 'cmp'))
{
    echo "success";
}
else
{
    echo "failure";
}

Solution

  • If you're not going to sort by the actual keys, don't use uksort but usort or uasort:

    function cmp($a, $b) {
        return $a['val2'] - $b['val2'];
    }
    
    uasort($arr, 'cmp');