note 66990 deleted from function.unset by bjori
| From: | bjori@php.net | Date: | Fri, 02 Jun 2006 06:18:10 +0000 |
| Subject: | note 66990 deleted from function.unset by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-112877@lists.php.net to get a copy of this message | ||
Note Submitter: aldarn at xenwars dot com
Reason: bad code
----
One problem i came across while using this function to destroy an element of an array, was that it
left the keys of an array "jumbled up". For example:
<?php
$array = ("10","5","3","1","7");
unset($array[2]);
unset($array[3]);
print_r($array);
?>
This gives:
array
{
[0] => 10
[1] => 5
[4] => 7
}
Note that, the keys have been left as before, rather than sorted into 0, 1, 2.
To fix this,the following can be used:
<?php
$array = ("10","5","3","1","7");
unset($array[2]);
unset($array[3]);
$new_array = array();
end($array); // Set the pointer to end of the array
$loop = key($array); // Get the last key of the array (which is the number we're counting to!)
reset($array); // Reset pointer back to start
for($i=0;$i<=$loop;$i++)
{
if(array_key_exists($i,$array))
array_push($new_array,$array[$i]);
}
print_r($new_array);
?>
This gives:
new_array
{
[0] => 10
[1] => 5
[2] => 7
}
What we have done is basically, create a new array, and cycled through all the old array, adding any
values where there was a key into the new array, until we had cycled to the last key in the old
array.
Hope this helps!