Bug #3964 Updated: unset element reappearing in 2 dimensions array after u(a)sort.
| From: | sterling@php.net | Date: | Sun, 09 Sep 2001 13:40:25 +0000 |
| Subject: | Bug #3964 Updated: unset element reappearing in 2 dimensions array after u(a)sort. | ||
| References: | 1 | Groups: | php.dev |
| Request: | Send a blank email to php-dev+get-65575@lists.php.net to get a copy of this message | ||
ID: 3964
Updated by: sterling
Reported By: laurent30@hotmail.com
Old Status: Open
Status: Closed
Bug Type: Misbehaving function
Operating System: linux
PHP Version: 3.0.14
New Comment:
fixed in php4
Previous Comments:
------------------------------------------------------------------------
[2000-03-29 15:53:17] laurent30@hotmail.com
When sorting a 2 dimension array in which 1 (or more) elements have been
unset, those unset element reappear in the array (with an empty value).
Example script :
<?php
error_reporting(63);
$my_array = array();
function Show_array($my_array) //Show array elements
{
reset($my_array);
while(list($idx,$sub_array) = each($my_array))
print("index $idx, name ".$sub_array['name'].", level
".$sub_array['level']."<BR>");
print("count (my_array) = ".count($my_array)."<BR>");
}
function sort_array($a, $b)
{
if ($a['level'] == $b['level']) return 0;
return ($a['level'] > $b['level']) ? -1 : 1;
}
//fill the array for test purpose
$my_array['a'] = array('name'=>'test1', 'level'=>1);
$my_array['b'] = array('name'=>'test2', 'level'=>2);
$my_array['c'] = array('name'=>'test3', 'level'=>3);
$my_array['d'] = array('name'=>'test4', 'level'=>4);
$my_array['e'] = array('name'=>'test5', 'level'=>5);
Show_array($my_array); //Show original array
print("<b><u>Now I remove 1 element of the array
:</u></b><br>");
unset($my_array['b']);
Show_array($my_array); //Show array with 'b' element removed
print("<b><u>and now I sort the array :(:(:(:(:(:(:(
:</u></b><br>");
// usort($my_array, 'sort_array'); //<- problem
uasort($my_array, 'sort_array'); //<- problem
// ksort($my_array); //<- NO problem
Show_array($my_array); //Show array after sorting ... 'b' element is back :-(
?>
As you can see, after the usort function is applied, the number of
element in the array is 5 again, with element 'b' beeing empty. The
solution I found is to unset empty element after the sort.
Another solution (found by a friend) is to add this line at the beginning of the
sort_array() : if(!is_array($a)||!is_array($b)) return 0;
Thanks for your support :-)
------------------------------------------------------------------------
Edit this bug report at http://bugs.php.net/?id=3964&edit=1