PHP Delete all occurrences of an element from an array

Erasing all events of components in PHP: Here, we will figure out how to evacuate/erase all events of a given component from an exhibit in PHP?

Given a cluster and we need to evacuate all events of a component from it.

array_diff() function

To expel all events of a component or numerous components from an exhibit – we can utilize array_diff() function, we can just make a cluster with at least one components to be erased from the exhibit and pass the cluster with erased element(s) to the array_diff() as a subsequent parameter, first parameter will be the source exhibit, array_diff() function restores the components of source exhibit which don’t exist in the subsequent (exhibit with the components to be erased).

PHP code to expel all events of a component from an exhibit

<?php
//array with the string elements
$array = array('the','quick','brown','fox','quick','lazy','dog');

//array with the elements to be delete 
$array_del = array('quick');

//creating a new array without 'quick' element
$array1 = array_values(array_diff($array,$array_del));
//printing the $array1 variable
var_dump($array1);

//now we are removing 'the' and 'dog'
//array with the elements to be delete 
$array_del = array('the', 'dog');

//creating a new array without 'the' and 'dog' elements
$array2 = array_values(array_diff($array,$array_del));
//printing the $array2 variable
var_dump($array2);
?>

Output

array(5) {
  [0]=>   
  string(3) "the"
  [1]=>   
  string(5) "brown"
  [2]=>   
  string(3) "fox"
  [3]=>   
  string(4) "lazy" 
  [4]=>   
  string(3) "dog"
}         
array(5) {
  [0]=>   
  string(5) "quick"
  [1]=>   
  string(5) "brown"
  [2]=>   
  string(3) "fox"
  [3]=>   
  string(5) "quick"
  [4]=>   
  string(4) "lazy" 
}

Clarification:

We utilize the array_diff() strategy to compute the distinction between two exhibits which basically wipes out all the events of a component from $array, on the off chance that they show up in $array_del. In the given example, we erase all the events of the words fast and darker from $array utilizing this technique.

Leave a Comment

error: Alert: Content is protected!!