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
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
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.
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.
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]);
}
how to just delete "blue"?
Here you go:
$input = array("red", "green", "blue", "yellow");
array_splice($input, array_search('blue', $input), 1);