...

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



Ultragames
10-20-2004, 05: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!

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

unset($arrayname[keyyouwannaremove]);

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)

Fou-Lu
10-20-2004, 10: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.

trib4lmaniac
10-20-2004, 11:41 AM
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).

trib4lmaniac
10-20-2004, 03: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.

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

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

Ultragames
10-21-2004, 05: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.

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

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

Thanks for all your help guys!!

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum