Home » PHP » PHP Examples

PHP | Delete all occurrences of an element from an array

Deleting all occurrences of an elements in PHP: Here, we are going to learn how to remove/delete all occurrences of a given element from an array in PHP?
Submitted by Bhanu Sharma, on August 10, 2019

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).

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.