note 66990 added to function.unset
| From: | aldarn at xenwars dot com | Date: | Fri, 02 Jun 2006 02:23:28 +0000 |
| Subject: | note 66990 added to function.unset | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-112852@lists.php.net to get a copy of this message | ||
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!
----
Server IP: 85.116.0.130
Probable Submitter: 200.55.87.254
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.unset.php
Edit -- http://master.php.net/note/edit/66990
Del: integrated -- http://master.php.net/note/delete/66990/integrated
Del: useless -- http://master.php.net/note/delete/66990/useless
Del: bad code -- http://master.php.net/note/delete/66990/bad+code
Del: spam -- http://master.php.net/note/delete/66990/spam
Del: non-english -- http://master.php.net/note/delete/66990/non-english
Del: in docs -- http://master.php.net/note/delete/66990/in+docs
Del: other reasons-- http://master.php.net/note/delete/66990
Reject -- http://master.php.net/note/reject/66990
Search -- http://master.php.net/manage/user-notes.php