$v){if($v==1){$r[]=$k;}}" will return a result array containing all unique elements; 3. Use count() gets the length of the result array, the syntax is "count($r)"."/> $v){if($v==1){$r[]=$k;}}" will return a result array containing all unique elements; 3. Use count() gets the length of the result array, the syntax is "count($r)".">
Home > Article > Backend Development > How to get the number of unique elements in an array in php
Implementation steps: 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 and assign it a value. Given an empty array, the syntax "foreach(associative array as $k=>$v){if($v==1){$r[]=$k;}}" will return an array containing all unique elements. The result array; 3. Use count() to get the length of the result array, the syntax is "count($r)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In php, you can use array_count_values() and The count() function obtains the number of unique elements in an array.
Implementation steps:
Step 1: Use array_count_values() to count the number of occurrences of elements
array_count_values() function can count The number of occurrences of all values in the array; if the number is 1, the element is not 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.
<?php header('content-type:text/html;charset=utf-8'); $arr=array("A","Cat","Dog","A","Dog","a",3,4); var_dump($arr); $count=array_count_values($arr); var_dump($count); ?>
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.
Step 2: Use the foreach statement to traverse the associative array, obtain the key name of the element with a key value of 1, and assign it to an empty array
$result=[]; foreach($count as $k=>$v){ if($v==1){ $result[]=$k; } } var_dump($result);
Will return a result array containing all non-repeating elements
Step 3: Use the count() function to obtain the length of the result array, that is, count the number of elements in the array
$len=count($result); echo "不重复元素的个数为:".$len;
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to get the number of unique elements in an array in php. For more information, please follow other related articles on the PHP Chinese website!