Say I had an array called $name with the following: $name[0] = "Bob"; $name[1] = "Ben"; $name[2] = "Sarah"; $name[3] = "Mike"; $name[4] = "John"; $name[5] = "Dave"; $name[6] = "Sue"; $name[7] = "Sam"; $name[8] = "Terry"; $name[9] = "Geff"; Now for whatever reason I want to delete element 4. And anything below it (in this case 5-9, but this is dynamic) would move up an index, resulting in: $name[0] = "Bob"; $name[1] = "Ben"; $name[2] = "Sarah"; $name[3] = "Mike"; $name[4] = "Dave"; $name[5] = "Sue"; $name[6] = "Sam"; $name[7] = "Terry"; $name[8] = "Geff"; What is the best way to do this in PHP?
you could loop and unset $start=4; $end=count($name); for ($i=$start;$i<=$end;$i++) { unset $name[$i]; } I haven't tried that by the way
Wouldn't that remove all elements from the array from $start to $end? I only want in this case to remove $start, and reindex $start+1 to be $start and $start+2 to be $start+1 and so forth (so element $name[5] becomes $name[4] (while still being "Dave"), 6 becomes 5, etc). Thanks for your help too BTW...
$tmp=$name; array_shift($name); $end=4; for ($i=1;$i<=$end;$i++) { $name[$i]=$tmp[$i]; } I guess you could split the array use array_shift to move the values down and then put the part of the old array back There must be a more elegant way to do that
After you unset the element(s) you want, you could: sort($name); ...and that should reindex the whole array. The names will be in a different order, if that matters, but it seems that you just don't want any gaps in the indexs?
Thanks guys, yeah unfortunetly it does matter I want the names to be in the same order, but the ones that were after the removed element moved up an index (while maintaining order) as per example in the top post,
That's a very sweet solution, Lucky Bastard. I tested it, and It's super-fast, too. I was about to post another solution, but yours has to be the very best. Salsa _______