OneBite.Dev - Coding blog in a bite size

Remove A Specific Element From An Array In PHP

Code snippet for how to Remove A Specific Element From An Array In PHP with sample and detail explanation

Working with arrays is a common task in any programming language. In this article, we will explore how to remove a specific element from an array in PHP in a very simple and efficient way.

Code snippet for Removing Specific Element From an Array In PHP

<?php
$yourArray = array('one', 'two', 'three', 'four', 'five');
$elementToRemove ='three';

if(($key = array_search($elementToRemove, $yourArray)) !== false) {
    unset($yourArray[$key]);
}
print_r($yourArray);
?>

Code Explanation for Removing Specific Element From an Array In PHP

In the provided PHP code snippet, we first define an array named $yourArray with five elements: ‘one’, ‘two’, ‘three’, ‘four’, ‘five’. Then we specify the element we want to remove from the array, 'three', and store it in the $elementToRemove variable.

The array_search() function is the main player in this code. This function searches for the specified element in the array. If it finds the element, it returns the key of that element. If the element is not found, it returns false.

The returned key is then stored in the $key variable. We use the strict comparison operator !== to compare the returned $key with false. If they are not identical (which means the element was found in the array), the if condition will be true.

Inside the if block, we use the unset() function to remove the element from the array. The unset() function in PHP allows us to unset (or remove) a certain variable or an array element. We just need to pass the element we want to remove (in this case, $yourArray[$key]) as its argument.

Finally, we use the print_r() function to print the $yourArray to check whether the specific element has been removed. The output will be:

Array ( [0] => one [1] => two [3] => four [4] => five )

As you can see, the ‘three’ element has been successfully removed from the array.

php