note 44184 added to function.unset
| From: | anonatnospamdotnoaddressdotcom at rn2 dot php dot net | Date: | Sat, 17 Jul 2004 01:19:29 +0000 |
| Subject: | note 44184 added to function.unset | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-73427@lists.php.net to get a copy of this message | ||
Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of
the array, if you use unset, the next index value will still be what it would have been.
Eg you have
<?php
$x = array(1, 2);
for ($i = 0; $i < 5; $i++)
{
unset($x[(count($x)-1)]); //remove last set key in the array
$x[] = $i;
}
?>
You would expect:
Array([0] => 1, [1] => 4)
as you want it to remove the last set key....
but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )
This is since even though the last key is removed, the auto indexing still keeps its previous value.
The only time where this would not seem right is when you remove a value off the end. I guess
different people would want it different ways.
The way around this is to use array_pop() instead of unset() as array_pop() refreshes the
autoindexing thing for the array.
<?php
$x = array(1, 2);
for ($i = 0; $i < 5; $i++)
{
array_pop($x); // removes the last item in the array
$x[] = $i;
}
?>
This returns the expected value of x = Array([0] => 1, [1] => 4);
Hope this helps someone who may need this for some odd reason, I did.
----
Manual Page -- http://www.php.net/manual/en/function.unset.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44184
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44184&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44184&report=yes
Search -- http://master.php.net/manage/user-notes.php