PHP has the built-in function called array_splice()
to remove an item from an array. However, the function alone does not help you remove a certain item from an array. Since I just wrote an article on this topic for JavaScript, it’s only proper I cover it in PHP as well.
It’s easy to remove a specific item from an array. We will simply wrap our array_splice()
function in a loop and look for our item. A key part of this loop is that it starts at the end and goes backwards.
Here is a breakdown of what we will do in 3 easy steps, so that you can implement this solution yourself later.
The Three Step Process
- Setup a basic loop that iterates backwards
- In the loop, test for matching items
- Use array_splice() on matching items during the loop
Solid Tip: array_splice()
needs at least 3 arguments: array_splice ( $array, $offset, $length )
. If you don’t specify the 3rd argument, everything after the offset is removed.
Removing One Item
Here is our code example using the traditional fruit array. In this example, I want to remove ‘banana’ if it exists.
$myArray = array('apple','orange','banana','pear','peach'); for($i = sizeof($myArray)-1; $i >= 0; $i--){ // STEP 1 if($myArray[$i] == 'orange'){ // STEP 2 array_splice($myArray,$i,1); // STEP 3 } } // returns the array (apple,banana,pear,peach) |
Removing Multiple Items
The third argument in array_splice()
controls how many items are removed from the starting offset. If we used the integer 2 instead of 1 in Step 3 above, we would have removed both ‘orange’ and ‘banana.’ That does not help us if we want to remove 2 or more specific items, though.
If you want to test for 2 specific values, make a simple modification to step 2, as seen below. Here I will look for and remove both ‘banana’ and ‘peach.’
$myArray = array('apple','orange','banana','pear','peach'); for($i = sizeof($myArray)-1; $i >= 0; $i--){ // STEP 1 if($myArray[$i] == 'apple' || $myArray[$i] == 'orange'){ // STEP 2 array_splice($myArray,$i,1); // STEP 3 } } // returns the array (apple,orange,pear) |
Did you consider unset( $myArray[ array_search( ‘orange’ , $myArray ) ] ) ?
Actually, I would prefer to use a shorter syntax like that but the result would be different. That short way leaves an empty void in the array that might cause unpredictable results when using it later:
My way leaves a normal looking array 0,1,2,3…
Array ( [0] => apple [1] => banana [2] => pear [3] => peach )
That short way leaves a missing array key 0,2,3,4…
Array ( [0] => apple [2] => banana [3] => pear [4] => peach )