php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #3964 unset element reappearing in 2 dimensions array after u(a)sort.
Submitted: 2000-03-29 15:53 UTC Modified: 2001-09-09 09:40 UTC
From: laurent30 at hotmail dot com Assigned:
Status: Closed Package: Misbehaving function
PHP Version: 3.0.14 OS: linux
Private report: No CVE-ID: None
 [2000-03-29 15:53 UTC] laurent30 at hotmail dot 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 :-)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-09-09 09:40 UTC] sterling@php.net
fixed in php4
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu May 02 03:01:29 2024 UTC