Is there a simple way to remove an element from an array in PHP?

Is there a simple way to remove an element from an array in PHP so that foreach ($array) no longer includes that element?

I initially tried setting the element to null, but that doesn’t seem to work.

Hey Neha,

I am not sure if there is a simple way, but using unset() function can help you

The unset() function to remove an element from an array. This will completely remove the element, and foreach will no longer iterate over it.

$array = [1, 2, 3, 4];
unset($array[2]); // Remove the element with index 2

foreach ($array as $value) {
    echo $value . "\n";
}

Output will be:

1 2 4

Hey Neha,

Using array_splice() : You can also use the array_splice() function to remove an element. This function can remove elements and reindex the array.

$array = [1, 2, 3, 4];
array_splice($array, 2, 1); // Remove 1 element at index 2

foreach ($array as $value) {
    echo $value . "\n";
}

The output will be: 1 2 4

Explanation: array_splice() removes elements from an array and shifts the indices of the remaining elements, ensuring the array remains contiguous.

Hey Neha,

Using array_filter() : You can use array_filter() to remove elements based on a condition. This is useful if you want to remove elements that meet certain criteria.

$array = [1, 2, 3, 4];
$array = array_filter($array, function($value) {
    return $value !== 3; // Remove element with value 3
});
foreach ($array as $value) {
    echo $value . "\n";
}

Output will be: 1 2 4

Explanation: array_filter() filters elements based on a callback function. Elements that do not meet the criteria (in this case, not equal to 3) are removed. This function does not reindex the array, but foreach will still skip over any removed elements.

Hope this array_filter() method works for you :slight_smile: