usort() implementation in 4.1+
| From: | Phil Dier | Date: | Fri, 26 Jul 2002 17:10:27 +0000 |
| Subject: | usort() implementation in 4.1+ | ||
| Groups: | php.dev | ||
| Request: | Send a blank email to php-dev+get-86245@lists.php.net to get a copy of this message | ||
I'm sure this has been discussed on here already, but I just discovered the usort() behaviour
that was
introduced in php 4.1.0 relating to "equal" values. Consider this scenario:
<?
class data_object
{
var $id;
var $time;
function data_object($id, $time)
{
$this->id = $id;
$this->time = $time;
}
function do_sort($a,$b)
{
if($a->time == $b->time) return 0;
return ($a->time > $b->time) ? 1 : -1;
}
}
$a3 = new data_object(3, 400);
$a2 = new data_object(2, 400);
$a1 = new data_object(1, 400);
$o_array[0] = &$a1;
$o_array[1] = &$a2;
$o_array[2] = &$a3;
echo "<pre>";
print_r($o_array); // the array is in the right order here...
echo "</pre>";
usort($o_array, array("data_object","do_sort"));
echo "<pre>";
print_r($o_array); // here it's apparently in the order it is stored in memory...
echo "</pre>";
?>
There's obviously a couple workarounds in this simple case, but adding more member vars and
defining
objects in different places complicates things. This behaviour is a bug IMO. And yes I saw the
note in
the manual, but i still think this is counter-intuitive and has the chance to break people's
code (it broke
mine).
Phil Dier <phil@gettcomm.com>
gett communications <http://www.gettcomm.com>
gett labs, inc. <http://www.gettlabs.com>