note 109329 modified in function.usort by danbrown

From: Date: Mon, 16 Jul 2012 15:45:09 +0000
Subject: note 109329 modified in function.usort by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189220@lists.php.net to get a copy of this message
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.&#13;&#10;&#13;&#10;&#60;?php&#13;&#10;class TestObj {&#13;&#10; private $name;&#13;&#10; private $id;&#13;&#10;&#13;&#10; function TestObj($name, $id) {&#13;&#10; $this-&#62;name = $name;&#13;&#10; $this-&#62;id = $id;&#13;&#10; }&#13;&#10;&#13;&#10; static function cmp_obj($a, $b) {&#13;&#10; $al = strtolower($a-&#62;name);&#13;&#10; $bl = strtolower($b-&#62;name);&#13;&#10; if ($al == $bl) {&#13;&#10; return 0; // return 1 if you don&#39;t want $b to go in front of $a&#13;&#10; }&#13;&#10; return ($al &#62; $bl) ? +1 : -1;&#13;&#10; }&#13;&#10;}&#13;&#10;&#13;&#10;$a[] = new TestObj(&#34;a&#34;, 1);&#13;&#10;$a[] = new TestObj(&#34;a&#34;, 2);&#13;&#10;$a[] = new TestObj(&#34;a&#34;, 3);&#13;&#10;&#13;&#10;var_dump($a);&#13;&#10;usort($a, array(&#34;TestObj&#34;, &#34;cmp_obj&#34;));&#13;&#10;var_dump($a);&#13;&#10;?&#62; --was-- 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); http://php.net/manual/en/function.usort.php

« previous php.notes (#189220) next »