OneBite.Dev - Coding blog in a bite size

Remove Item From Array In PHP

Code snippet for how to Remove Item From Array In PHP with sample and detail explanation

Removing items from an array is a common task in PHP programming. This article will guide you through the process with a simple step-by-step tutorial.

Code snippet for removing item from array in PHP

$array = array("apple", "banana", "orange", "pineapple");
if(($key = array_search("banana", $array)) !== false) {
   unset($array[$key]);
}

print_r($array);

Code Explanation for removing item from array

Our PHP script starts by creating an array of fruits.

$array = array("apple", "banana", "orange", "pineapple");

Next, we use array_search() to find the key/index of the item we want to remove. In our case, we’ve specified “banana”.

$key = array_search("banana", $array);

The array_search() method returns the key for array elements that matches the specified value. If the value is not found, this method will return false.

The !== false in our if statement ensures that even if the array key is 0, the statement is still truthy (since 0 is falsy in PHP).

So, if our specified element (“banana”) is found inside the array, it will give us the key/index of that value.

Next is the actual removal of the element, PHP’s unset() function is used to destroy the specified variables.

unset($array[$key]);

Here, $array[$key] would correspond to the “banana” element in our array, which will be removed from the array.

Finally, we print out the updated array, which will no longer includes “banana”.

print_r($array);

This will output:

Array ( [0] => apple [2] => orange [3] => pineapple )

So, you can see that the “banana” is removed from the array.

Hope you find this quick guide helpful for understanding how to remove an item from an array using PHP. Remember that coding takes practice, so do work on real-time examples for good grasp and understanding.

php