note 81815 modified in function.usort by thiago

From: Date: Tue, 22 Jul 2008 19:09:52 +0000
Subject: note 81815 modified in function.usort by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142554@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. <?php 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. ) --was-- 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. ) http://php.net/manual/en/function.usort.php

« previous php.notes (#142554) next »