| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [2010-01-07 19:42 UTC] jcampbell at remindermedia dot com
 Description:
------------
If the callback function used by usort handles an exception using a try/catch block, a warning is generated. The correct sorting is still done. This happens even when the exception & handling doesn't involve the variables.
The example below is the usort example from the manual with only the try/catch block added. Reproducible in PHP 5.2.11 but not 5.2.9
Reproduce code:
---------------
<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    try {
        throw new Exception();
    } catch (Exception $E) {
    }
    return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
Expected result:
----------------
No warning message.
Actual result:
--------------
PHP Warning:  usort(): Array was modified by the user comparison function in /home/jcampbell/usortExceptionWarning.php on line 19
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 07:00:01 2025 UTC | 
I'd like to add, that you do not have to throw an exception to get this warning. Mere creating it, also triggers the warning, as in: <?php function comp($a,$b){ @new Exception("dupa"); } $a =array(1,2,3); usort($a, 'comp'); var_dump($a); ?> PHP Warning: usort(): Array was modified by the user comparison function in /home/jlopuszanski/test.php on line 6I ran into a similar issue, i'm sure it'll require the same patch as it's the backtrace causing the problem but worth noting it doesn't require an exception to trigger this, just a backtrace. $ cat usort.php <?php set_error_handler(function($errno, $errstr) { $bt = debug_backtrace(); var_dump($errstr); }); $arr = [1, 2]; usort($arr, function($a, $b) use ($arr) { trigger_error('test'); return $a > $b; }); $ php usort.php string(4) "test" string(59) "usort(): Array was modified by the user comparison function"A notice within the compare function will also trigger this notice. For example: function test($a, $b) { return strnatcmp($a['name'], $b['name']); } $e = array( array( 'not-name' => 'a', ), array( 'name' => '', ), ); uasort($e, 'test'); (this is tested on PHP 5.3)