First of all, I'd like to point out to all you duplicate question hunters that this question does not fully answer my question.
Now, I've got an array. We'll say that the array is array(1, 2, 2, 3, 4, 3, 2)
I need to remove the duplicates. Not just one of the duplicates, but all, so that the result will be array(1, 4)
I looked at array_unique(), but that will only result in array(1, 2, 3, 4)
Any ideas?
We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.
An array is defined and duplicate elements from the array can be found and removed using the 'array_flip' function, that basically reverses the keys/index as values and values as keys.
A user-defined function can help in getting unique values from multidimensional arrays without considering the keys. You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys.
You could use the combination of array_unique
, array_diff_assoc
and array_diff
:
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
function removeDuplicates($array) {
$valueCount = array();
foreach ($array as $value) {
$valueCount[$value]++;
}
$return = array();
foreach ($valueCount as $value => $count) {
if ( $count == 1 ) {
$return[] = $value;
}
}
return $return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With