note 100183 added to function.usort
| From: | fmaz008 at gmail dot com | Date: | Wed, 29 Sep 2010 21:23:36 +0000 |
| Subject: | note 100183 added to function.usort | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172826@lists.php.net to get a copy of this message | ||
This comment is just to help backward compatibility.
I needed to have a foreach loop using reference just before using the usort function on the same
array that was used in the foreach.
Like this:
<?php
public function sortByTitle()
{
if(empty($this->_arrSubCat))
return false;
foreach($this->_arrSubCat as &$cat)
$cat->sortByTitle();
usort($this->_arrSubCat, 'strcasecmp');
}
?>
I had this strange bug where the last object of the $this->_arrSubCat array before the sort was
alway replaced/overwrited with his string value.
On my machine (PHP 5.3), I had no problem, but when I placed the code on another server, my code
crashed with a fatal error (Because I was using a string as an object later in the code)
The solution I found is really simple, and avoid the array to have a reference declared in memory
while running the sort function. Just add an unset($cat):
<?php
public function sortByTitle()
{
if(empty($this->_arrSubCat))
return false;
foreach($this->_arrSubCat as &$cat)
$cat->sortByTitle();
unset($cat); //No more problem because of the foreach &cat reference.
usort($this->_arrSubCat, 'strcasecmp');
}
?>
It took me an hour an a half to locate the bug, hope it will save someone some time !
----
Server IP: 72.55.140.6
Probable Submitter: 24.37.122.45
----
Manual Page -- http://www.php.net/manual/en/function.usort.php
Edit -- https://master.php.net/note/edit/100183
Del: integrated -- https://master.php.net/note/delete/100183/integrated
Del: useless -- https://master.php.net/note/delete/100183/useless
Del: bad code -- https://master.php.net/note/delete/100183/bad+code
Del: spam -- https://master.php.net/note/delete/100183/spam
Del: non-english -- https://master.php.net/note/delete/100183/non-english
Del: in docs -- https://master.php.net/note/delete/100183/in+docs
Del: other reasons-- https://master.php.net/note/delete/100183
Reject -- https://master.php.net/note/reject/100183
Search -- https://master.php.net/manage/user-notes.php