note 100183 deleted from function.usort by cmb
| From: | cmb@php.net | Date: | Sun, 13 Oct 2019 08:17:04 +0000 |
| Subject: | note 100183 deleted from function.usort by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212636@lists.php.net to get a copy of this message | ||
Note Submitter: fmaz008 at gmail dot com
----
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 !