note 81815 added to function.usort

From: Date: Fri, 14 Mar 2008 12:37:43 +0000
Subject: note 81815 added to function.usort
Groups: php.notes 
Request: Send a blank email to php-notes+get-137055@lists.php.net to get a copy of this message
From the docs the user defined function looks as it could be arbitrary. This is not the case. I needed a comparison that would send arbitrary values at the end of the array. Say '0' means invalid for example. So here is a sample function. function array_cmp($a, $b) { if( $a == 0 ) { return 99; } elseif( $a > $b ) { return 1; } elseif( $a == $b ) { return 0; } elseif( $a < $b ) { return -1; } } usort($test_array, "array_cmp"); print '<pre>'; print_r( $test_array ); print '</pre>'; $test_array = array( 'a' => 8 , 'b' => 0 , 'c' => 1 , 'd' => 0 , 'e' => 3 ); Output: Array ( [0] => 0 [1] => 1 [2] => 8 [3] => 0 [4] => 3 ) This is beacause comparisons aren't applied to all possible pairs. So when the '0' is tested as $b strange things can occur... This is solved simply adding an } elseif( $b == 0) { return -99; } statement. Carefull of the pitfalls. If you alter the ordering in strange ways without knowledge in the underlying algorithm one could even trigger infinite loops. (if your testing for $a and $b for the same value give inconsistent results. ) ---- Server IP: 80.241.173.254 Probable Submitter: 85.18.76.4 ---- Manual Page -- http://www.php.net/manual/en/function.usort.php Edit -- https://master.php.net/note/edit/81815 Del: integrated -- https://master.php.net/note/delete/81815/integrated Del: useless -- https://master.php.net/note/delete/81815/useless Del: bad code -- https://master.php.net/note/delete/81815/bad+code Del: spam -- https://master.php.net/note/delete/81815/spam Del: non-english -- https://master.php.net/note/delete/81815/non-english Del: in docs -- https://master.php.net/note/delete/81815/in+docs Del: other reasons-- https://master.php.net/note/delete/81815 Reject -- https://master.php.net/note/reject/81815 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#137055) next »