Remove specific element by value from an array in PHP?

Description:

You need to write a program in PHP to remove specific element by value from an array using PHP program.

Instructions:

  • Take an array with list of month names.
  • Take a variable with the name of value to be deleted.
  • You can use PHP array functions or foreach loop.

Solution 1: Using array_search()

With the help of array_search() function, we can remove specific elements from an array.

<?php
$delete_item = 'march';
// take a list of months in an array
$months = array('jan', 'feb', 'march', 'april', 'may');
if (($key = array_search($delete_item, $months)) !== false) {
    unset($months[$key]);
}
 
// print array to see latest values
var_dump($months);
?>
Tutorials Class - Output Window

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }


Solution 2: Using foreach()

By using foreach() loop, we can also remove specific elements from an array.

<?php
$delete_item = 'april';
// take a list of months in an array
$months = array('jan', 'feb', 'march', 'april', 'may'); // for april, the key is 4
foreach (array_keys($months, $delete_item) as $key) {
    unset($months[$key]);
}

// print array to see latest values
var_dump($months);
?>
Tutorials Class - Output Window

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [3]=> string(5) “april” [4]=> string(3) “may” }


Solution 3: Using array_diff()

With the help of array_diff() function, we also can remove specific elements from an array.

<?php
$delete_item = 'april';
// take a list of months in an array
$months= array('jan', 'feb', 'march', 'april', 'may');
$final_months= array_diff($months, array($delete_item));
 
// print array to see latest values
var_dump($final_months);
?>
Tutorials Class - Output Window

array(4) { [0]=> string(3) “jan” [1]=> string(3) “feb” [2]=> string(5) “march” [4]=> string(3) “may” }


Learn more about the similar topics:
Tutorials
PHP Arrays
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
No Content Found.