Home>Article>Backend Development> How to find unique elements in an array in php
Method: 1. Use array_count_values() to count the number of occurrences of elements and return an associative array; 2. Traverse the associative array and determine whether the value is 1. If it is 1, take out the corresponding key name. The syntax "foreach(array as $k=>$v){if($v==1){$r[]=$k;}}".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
How to find an array in php Unrepeated elements in
In PHP, you can use the array_count_values() function to find out the unique elements in an array.
array_count_values() function can count the number of occurrences of all values in the array; if the number is 1, the element will not be repeated.
array_count_values() function will return an associative array, the key name of its element is the value of the original array, and the key value is the number of times the value appears in the original array.
It can be seen that in the associative array, the element with a key value of 1 is a non-repeating element. Just get the corresponding key name.
Just use the foreach statement to traverse the associative array, get the key name of the element with the key value 1, and assign it to an empty array.
$result=[]; foreach($count as $k=>$v){ if($v==1){ $result[]=$k; } } var_dump($result);
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find unique elements in an array in php. For more information, please follow other related articles on the PHP Chinese website!