Remove specific element by value from an array in PHP?

Description: Write a PHP program to remove a specific element, by its value, from an array.

Rules and hints:

  • Take an array with the names of some months.
  • Take a variable with the value that you want to remove.
  • You can use array functions or a foreach loop.

Solution 1: array_search() and unset()

array_search() finds the key of the value, and unset() removes that key. The other keys are not changed.

<?php
$months = ["January", "February", "March", "April", "May"];
$remove = "March";

$key = array_search($remove, $months);

if ($key !== false) {
    unset($months[$key]);
}

print_r($months);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => January
[1] => February
[3] => April
[4] => May
)

Solution 2: array_diff()

array_diff() removes all matching values (also if the value is many times in the array). Use array_values() to get new keys 0, 1, 2…

<?php
$months = ["January", "February", "March", "April", "May"];
$remove = "March";

$months = array_values(array_diff($months, [$remove]));

echo implode(", ", $months);
?>

Output:

Tutorials Class - Output Window

January, February, April, May

Solution 3: array_filter()

<?php
$months = ["January", "February", "March", "April", "May"];
$remove = "March";

$months = array_filter($months, fn($month) => $month !== $remove);

echo implode(", ", $months);
?>

Output:

Tutorials Class - Output Window

January, February, April, May

Note that solution 1 removes only the first match, but solutions 2 and 3 remove every match.


Learn more about the similar topics:
Tutorials
PHP Arrays
PHP Array Functions
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
What are the different PHP functions to sort an array?
PHP’s numerically indexed array begins with which position?
Which PHP function inserts an element to the end of an array?
Which PHP function can be used check if variable is an array?
How many types of arrays are available in PHP?
What is the use of array_chunk() function in PHP?
What is the use of in_array() function in PHP?