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 |
| Interview Questions & Answers |
|---|
| No Content Found. |