View Full Version : removing an array entry in the middle of an array

10-20-2004, 06:05 AM
I tried using a combination of array_shift() and array_splice() to remove a line from an array, and push everything back. What i mean is, of an array with 6 vaules, remove the 4th vaule, and change 5 and 6, to 4 and 5.

How can I do this?

Thank you!

10-20-2004, 11:35 AM
I believe i do it with


not sure what you exactly want. Like your index thing (6 to 5 etc). If it's just a unidimensional array with only the values, then simply removing an element would be enough. If you have a $key->$value type of array, then you'd need soething a bit more complex, but i can't quite see any function for the keys then.
maye post the array-structure (a print_r() of such an array)

10-20-2004, 11:39 AM
Yeah, I was going to say that I have heard of no function to easily reset your index keys. And as raf said if you have a $key for $value structure for them, I would recommend chaning it so you have named your key values instead: 'id' => 1, 'name' => 'your name' etc.

10-20-2004, 12:41 PM
I'm not sure if just unset-ing the value works (but it might). If it doesn't array_splice can do it with
$my_array = array_splice($my_array, N, N + 1);Which should chop out the Nth element (obviously change N to a number).

10-20-2004, 04:50 PM
Ok, got home and that didnt work :p so here...

function array_cut($arr, $n) {
$pre = array_slice($arr, 0, $n - 1);
$suf = array_slice($arr, $n);
foreach($suf as $sv) $pre[] = $sv;
return $pre;
should work for arrays with numeric indexes at least.

10-20-2004, 04:57 PM
Well I'm pretty sure that he doesn't care about associative arrays. ;)

10-20-2004, 05:02 PM
If he does (@ a later date) he can just use unset like raf said.

10-21-2004, 06:25 AM
unset dosn't change the index's. But after looking up that code, it was very usfull in stopping the user from refreshing the page, and doubling their order, so thank you for that.

As far as the splice, i got it to splice, i just coul't get it to keep the array entrys after the splice.

i ended up finding a way how to do it, although its not the best way im sure.

while( $i < sizeof($OrdersType) ){
if($number[$i] == "0"){
$temp = sizeof($OrdersType);
$stackType = array();
while( $j < $temp ){
if($j != $i){
array_push($stackType, $OrdersType[$j]);
$OrdersType = $stackType;

It puts the current entry into a new string unless its the one i dont want.

Thanks for all your help guys!!

10-21-2004, 01:30 PM
Well the function I posted earlier does work, so you can use that if you need to.