Bug #3964: unset element reappearing in 2 dimensions array after u(a)sort.

From: Date: Wed, 29 Mar 2000 20:53:18 +0000
Subject: Bug #3964: unset element reappearing in 2 dimensions array after u(a)sort.
Groups: php.dev 
Request: Send a blank email to php-dev+get-17358@lists.php.net to get a copy of this message
From: laurent30@hotmail.com Operating system: linux PHP version: 3.0.14 PHP Bug Type: Misbehaving function Bug description: unset element reappearing in 2 dimensions array after u(a)sort. 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 :-)

« previous php.dev (#17358) next »