Q:

PHP | Delete all occurrences of an element from an array

belongs to collection: PHP Array Programs

0

Given an array and we have to remove all occurrences of an element from it.

array_diff() function

To remove all occurrences of an element or multiple elements from an array – we can use array_diff() function, we can simply create an array with one or more elements to be deleted from the array and pass the array with deleted element(s) to the array_diff() as a second parameter, first parameter will be the source array, array_diff() function returns the elements of source array which do not exist in the second array (array with the elements to be deleted).

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

PHP code to remove all occurrences of an element from an array

<?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" 
}           

Explanation:

We use the array_diff() method to calculate the difference between two arrays which essentially eliminates all the occurrences of an element from $array, if they appear in $array_del. In the given example, we delete all the occurrences of the words quick and brown from $array using this method.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP | Find the occurrences of a given element in a... >>
<< PHP | Delete an element from an array using unset(...