note 22324 added to ref.array
| From: | msuchanek at desconnect dot om | Date: | Thu, 13 Jun 2002 19:13:47 +0000 |
| Subject: | note 22324 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-31829@lists.php.net to get a copy of this message | ||
I am working on a project wherein I had to delete something from an array, but I couldn't leave
a hole in the array.
For example:
<?php
$myarray[0] = "test0";
$myarray[1] = "test1";
$myarray[2] = "test2";
unset($myarray[1]);
for($i=0;$i<count($myarray);$i++) {
echo $i." = ".$myarray[$i]."<br>";
}
/*
Outputs this:
0 = test0
1 =
*/
?>
Obviously, that doesn't work. ;) I won't explain why, but you can probably figure that out
yourself.
Anyway, I wrote a function to correct this problem:
<?php
function deleteandpush($array, $indice) {
unset($array[$indice]);
for($i=0;$i<count($array);$i++) {
if(!isset($array[$i])) { $array[$i] = $array[$i+1]; unset($array[$i+1]); };
}
return $array;
}
$myarray[0] = "test0";
$myarray[1] = "test1";
$myarray[2] = "test2";
$myarray[3] = "test3";
$myarray[4] = "test4";
$array = deleteandpush($myarray, 3);
for($i=0;$i<count($array);$i++) {
echo $i.":".$array[$i]."<br>";
}
/*
Outputs:
0:test0
1:test1
2:test2
3:test4
*/
?>
Hope this helps someone.
--
http://www.php.net/manual/en/ref.array.php
http://master.php.net/manage/user-notes.php?action=edit+22324
http://master.php.net/manage/user-notes.php?action=delete+22324
http://master.php.net/manage/user-notes.php?action=reject+22324