Reputation: 2729
I'm trying to get all array elements, where the value only occurs once in the array.
I tried to use:
array_unique($array);
But this does only remove the duplicates, which is not what I want.
As an example:
$array = 0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
5 => 2
6 => 3
7 => 4
8 => 5
Expected output:
array(
0=>1
)
As you can see only the value 1 occurs once in the array, all other values are more than once in the array. So I only want to keep that one element.
Upvotes: 2
Views: 1716
Reputation: 59701
This should work for you:
First use array_count_values()
to count how many times each value is in your array. This will return something like this:
Array (
[1] => 1
[2] => 2
[3] => 2
[4] => 2
[5] => 2
// ↑ ↑
// Value Amount
)
After that you can use array_filter()
to only get the values, which occurs once in your array. Means:
Array ( [1] => 1 [2] => 2 [3] => 2 [4] => 2 [5] => 2 )
And at the end simply use array_keys()
to get the value from the original array.
Code:
<?php
$arr = [1,2,3,4,5,2,3,4,5];
$result = array_keys(array_filter(array_count_values($arr), function($v){
return $v == 1;
}));
print_r($result);
?>
output:
Array (
[0] => 1
)
Upvotes: 9
Reputation: 163
If you already have an array and it is in the structure described above, you should be able to just array_search(1, $array) and it will give you the key of the array with the value of 1. Or if you expect to have multiple keys with the value of 1, you can use array_keys($array, 1) and it will return an array of keys that have the value of 1. Hope this helps.
Upvotes: 0
Reputation: 35347
You can use array_count_values to get the number of times each value exists in the array. You can use this to get all the values that occur only once by looking at the value in the returned array.
Upvotes: 1