How to use array_filter() Function In PHP
The array_filter() function filters the elements of an array using a callback function. This method allows for custom logic to determine which elements to remove.
Example: This example shows the use of the above-explained approach.
<?php
// Declare an Array
$arr = [1, 2, 3, 4, 5, 6];
// Declare an array containing
// elements that need to remove
$remove = [2, 4, 6];
// Remove elements using array_filter
$result = array_filter($arr,
function($value) use ($remove) {
return !in_array($value, $remove);
});
print_r($result);
?>
Output
Array ( [0] => 1 [2] => 3 [4] => 5 )
Explanation:
- $arr is the original array.
- $remove contains the elements to be removed.
- array_filter($arr, function($value) use ($remove) { return !in_array($value, $remove); }) filters out the elements present in $remove.
How to Remove Multiple Elements from an Array in PHP?
Given an array containing some elements, the task is to remove some elements from the array in PHP.
Below are the approaches to remove multiple elements from an array in PHP:
Table of Content
- Using array_diff() Function
- Using array_filter() Function
- Using a Loop and unset() Function
- Using array_diff_key() Function