Remove Specific Element from an Array in PHP

Given an Array containing some elements, the task is to remove specific elements from the array in PHP.

Below are the approaches to remove specific elements from an array in PHP:

Table of Content

  • Using unset() Function
  • Using array_diff() Function
  • Using array_filter() Function
  • Using array_splice() Function
  • Using foreach Loop

Using unset() Function

The unset() function is used to remove an element from an array by its key. This method works well when you know the key of the element to be removed.

Example: The unset() function removes the element at index 1 (“CSS”) from the array.

PHP
<?php
$arr = ["HTML", "CSS", "JavaScript", "PHP"];
$key = 1;
unset($arr[$key]);
print_r($arr);
?>

Output
Array
(
    [0] => HTML
    [2] => JavaScript
    [3] => PHP
)

Using array_diff() Function

The array_diff() function compares arrays and returns the values in the first array that are not present in any of the other arrays. This can be used to remove specific elements by value.

Example: The array_diff() function removes the element “CSS” from the array.

PHP
<?php
$arr = ["HTML", "CSS", "JavaScript", "PHP"];
$remVal = "CSS";
$arr = array_diff($arr, [$remVal]);
print_r($arr);
?>

Output
Array
(
    [0] => HTML
    [2] => JavaScript
    [3] => PHP
)

Using array_filter() Function

The array_filter() function filters elements of an array using a callback function. This method allows for flexible conditions to remove elements.

Example: The array_filter() function removes the element “CSS” by returning false for that element in the callback function.

PHP
<?php
$arr = ["HTML", "CSS", "JavaScript", "PHP"];
$remVal = "CSS";
$arr = array_filter($arr, function($value) use ($remVal) {
    return $value !== $remVal;
});
print_r($arr);
?>

Output
Array
(
    [0] => HTML
    [2] => JavaScript
    [3] => PHP
)

Using array_splice() Function

The array_splice() function removes a portion of the array and can be used to remove an element by its key.

Example: The array_splice() function removes one element at index 1 (“CSS”) from the array.

PHP
<?php
$arr = ["HTML", "CSS", "JavaScript", "PHP"];
$key = 1;
array_splice($arr, $key, 1);
print_r($arr);
?>

Output
Array
(
    [0] => HTML
    [1] => JavaScript
    [2] => PHP
)

Using foreach Loop

A foreach loop can be used to create a new array without the element to be removed, which is particularly useful for associative arrays.

Example: The foreach loop iterates through the array and adds elements that do not match “CSS” to a new array.

PHP
<?php

$arr = ["HTML", "CSS", "JavaScript", "PHP"];
$remVal = "CSS";
$newArr = [];

foreach ($arr as $value) {
    if ($value !== $remVal) {
        $newArr[] = $value;
    }
}

print_r($newArr);

?>

Output
Array
(
    [0] => HTML
    [1] => JavaScript
    [2] => PHP
)