$ v){if($v==1){$r[]=$k;}}"."/> $ v){if($v==1){$r[]=$k;}}".">

Home  >  Article  >  Backend Development  >  How to find unique elements in an array in php

How to find unique elements in an array in php

青灯夜游
青灯夜游Original
2022-05-11 20:41:301723browse

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;}}".

How to find unique elements in an array in php

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.

How to find unique elements in an array in php

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);

How to find unique elements in an array in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn