|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2001-09-09 09:40 UTC] sterling@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 21:00:02 2025 UTC |
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 :-)