note 109329 deleted from function.usort by crell

From: Date: Thu, 31 Mar 2022 16:43:27 +0000
Subject: note 109329 deleted from function.usort by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217840@lists.php.net to get a copy of this message
Note Submitter: Jian Wu ---- The usort function actually moves $b up when the callback function returns both 0 and 1. If you want to preserve the original order in the array, return 1 when $a == $b instead of 0. Try this code below to see how usort alters the order of the original array when all values are the same. <?php class TestObj { private $name; private $id; function TestObj($name, $id) { $this->name = $name; $this->id = $id; } static function cmp_obj($a, $b) { $al = strtolower($a->name); $bl = strtolower($b->name); if ($al == $bl) { return 0; // return 1 if you don't want $b to go in front of $a } return ($al > $bl) ? +1 : -1; } } $a[] = new TestObj("a", 1); $a[] = new TestObj("a", 2); $a[] = new TestObj("a", 3); var_dump($a); usort($a, array("TestObj", "cmp_obj")); var_dump($a); ?>

« previous php.notes (#217840) next »