note 22324 deleted from ref.array by maxim

From: Date: Tue, 12 Nov 2002 16:08:02 +0000
Subject: note 22324 deleted from ref.array by maxim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-39386@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.

« previous php.notes (#39386) next »