tags:

views:

94

answers:

4

How do I delete a specific item by using array_splice/array_slice in PHP?

for example: array('a','b','c'); how to just delete 'b'? so the array remains: array('a','c');

Thanks

+1  A: 

Basically: Just do it.

The manual has good examples like this one:

$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

if something doesn't work out for you, please add more detail to your question.

Pekka
how to just delete "blue"?
lovespring
@lovespring you mean how to find the index position of "blue", correct?
Pekka
no, i mean, delete the "blue", just delete one item in the middle of the array.
lovespring
@lovespring it's already doing that, isn't it? I don't understand what your question is.
Pekka
your answer also delete the "yellow",so your array remains array('red','green'), i'm looking for a way to just delete the 'blue', so the array remains array('red','green','yellow'), thanks.
lovespring
@lovespring sorry, I didn't get that. That's what the third parameter `$length` is for. `array_splice($input, 2, 1)` should do the trick. Stuff like this is most often in the manual, make sure you check out the manual page first.
Pekka
+1  A: 

Starting with (id is the item you want to delete):

$input = array("a", "b", "c", "d", "e");
$id=2;

array splice:

$a1 = array_slice($input, $id);
print_r($a1);

Array
(
    [0] => c
    [1] => d
    [2] => e
)

array slice:

array_splice($input, $id-1);
print_r($input);

Array
(
    [0] => a
)

Merging the splice and the slice will give you an array that is the same as the input array but without the specific item.

You probably can do this using only one line but I'll leave that as an exercise for the readers.

zaf
+1  A: 

Does it have to be array_splice? I think the most appropriate way (maybe depending on the array size, I don't know how well array_search scales) is to use array_search() with unset():

$array = array('foo', 'bar' => 'baz', 'bla', 5 => 'blubb');

// want to delete 'baz'
if(($key = array_search('baz', $array)) !== FALSE) {
    unset($array[$key]);
}
Felix Kling
I know this way, first unset, then use array_values. thanks .
lovespring
+1  A: 

how to just delete "blue"?

Here you go:

$input = array("red", "green", "blue", "yellow");
array_splice($input, array_search('blue', $input), 1);
Alix Axel