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

  1. Setup a basic loop that iterates backwards
  2. In the loop, test for matching items
  3. 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)