In this tutorial, you shall learn how to delete all the occurrences of a specific value in given array in PHP using array_filter() function, with the help of example programs.

PHP – Delete specific element from array

To delete all the occurrences of a specific element in given array in PHP, we can use array_filter() function.

The syntax to remove all occurrences of a specific element value in an array arr using array_filter() function is

array_filter($arr, function ($var) use ($value) {
  return $var !== $value;
});

Examples

ADVERTISEMENT

1. Delete all the occurrences of the element “apple” from array

In this example, we will take an array with some elements, and delete the element "apple".

PHP Program

<?php
  $array = ["apple", "banana", "apple", "cherry"];
  $value = "apple";

  $filtered_array = array_filter($array, function ($item) use ($value) {
    return $item !== $value;
  });

  print_r($filtered_array);
?>

Output

Conclusion

In this PHP Tutorial, we learned how to delete all occurrences of a specific element in an array, using PHP Array array_filter() function.