PHP Tutorial

PHP Examples

PHP Practice

PHP | Delete all occurrences of an element from an array

Given an array, we have to how to remove/delete all occurrences of a given element from an array in PHP? By Bhanu Sharma Last updated : December 19, 2023

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

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.

PHP Array Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.