ID: 3964
Updated by: sterling
Reported By: [EMAIL PROTECTED]
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] [EMAIL PROTECTED]
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
--
PHP Development Mailing List <http://www.php.net/>
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]