Re: Bug #4159: Wrong count array after unset()
| From: | Faisal Nasim | Date: | Mon, 17 Apr 2000 07:42:44 +0000 |
| Subject: | Re: Bug #4159: Wrong count array after unset() | ||
| References: | 1 | Groups: | php.dev |
| Request: | Send a blank email to php-dev+get-17960@lists.php.net to get a copy of this message | ||
: $x=array(1,2,3,4,5,6,7,8);
:
: for($i=0; $i<count($x); $i++)
: echo $x[$i]."<br>\n";
:
: unset($x[2]);
: echo "<hr>";
:
: for($i=0; $i<count($x); $i++)
: echo $x[$i]."<br>\n";
You are using numerical keys, and the output is
correct.
When you unset ( $key [ 2 ] ), this is your array
structure
array ( 1 , 2 , 4 , 5 , 6 , 7 , 8 ) (count = 7)
And your loop is:
$i < 7
Which evaluates to:
$i [ 0 ] = 1
$i [ 1 ] = 2
$i [ 2 ] = BLANK // use array_splice to shift the values
$i [ 3 ] = 4;
$i [ 4 ] = 5;
$i [ 5 ] = 6;
$i [ 6 ] = 7;
$i [ 7 ] = 8; // never reaches here
But the loop goes from 0 to 6 ($i<7 is equiv to $i<=6)
This will solve your problem since it doesn't depend
upon numeric index:
for ( ; $i = current ( $x ) ; next ( $x ) )
print "$i<br>\n";
<cut>
Enjoy!
Faisal