Removing a specific item using array_splice / array_slice in PHP

How to delete a specific element using array_splice / array_slice in PHP?

for example: Array ('a', 'b', 's'); how to just remove 'b'? therefore the array remains: Array ('a', 'c');

thanks

+6
arrays php
source share
6 answers

Basically: just do it.

the manual has good examples like this:

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

If something doesn't work for you, add more details to your question.

+4
source share

In fact. I came up with two ways to do this. It depends on how you are going to deal with the index problem.

If you want to leave indices after removing certain elements from the array, you will need unset ().

 <?php $array = array("Tom","Jack","Rick","Alex"); //the original array /*Here, I am gonna delete "Rick" only but remain the indices for the rest */ unset($array[2]); print_r($array); ?> 

Output:

 Array ( [0] => Tom [1] => Jack [3] => Alex ) //The indices do not change! 

However, if you need a new array without saving the previous indexes, use array_splice ():

 <?php $array = array("Tom","Jack","Rick","Alex"); //the original array /*Here,we delete "Rick" but change indices at the same time*/ array_splice($array,2,1); // use array_splice() print_r($array); ?> 

The output this time:

 Array ( [0] => Tom [1] => Jack [2] => Alex ) 

Hope this helps!

+7
source share

how to simply remove the "blue"?

Here you go:

 $input = array("red", "green", "blue", "yellow"); array_splice($input, array_search('blue', $input), 1); 
+4
source share

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

 $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:

 array_splice($input, $id-1); print_r($input); Array ( [0] => a ) 

Merging splicing and slicing will give you an array that will be the same as the input array, but without a specific element.

You can probably do this using only one line, but I will leave this as an exercise for readers.

+1
source share

Should there be an array_splice ? I think the most appropriate way (perhaps depending on the size of the array, I don't know how good the array_search scales are) 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]); } 
+1
source share

Use array_diff :

 $array = array_diff($array , array('blue')); 
0
source share

All Articles