How to use array_filter() In PHP
To remove duplicate values from an array using `array_filter()`, apply a callback function that checks each element’s index against its first occurrence. Return true only for the first occurrence to filter out duplicates.
Example:
<?php
$array = [1, 2, 2, 3, 4, 4, 5];
$uniqueArray = array_filter($array, function($value, $key) use ($array) {
return array_search($value, $array) === $key;
}, ARRAY_FILTER_USE_BOTH);
print_r(array_values($uniqueArray));
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
How to remove duplicate values from array using PHP ?
In this article, we will discuss how to remove duplicate elements from an array in PHP. We can get the unique elements by using array_unique() function. This function will remove the duplicate values from the array.
Syntax
array array_unique($array, $sort_flags);
Note: The keys of the array are preserved i.e. the keys of the not removed elements of the input array will be the same in the output array.