Home  >  Article  >  Backend Development  >  如何判断数组里面有多少个相同元素?

如何判断数组里面有多少个相同元素?

WBOY
WBOYOriginal
2016-06-23 14:11:331286browse

$a=array('2','1','2');//如何判断里面有几个相同的元素,并且知道相同的元素在什么位置

求指点谢谢


回复讨论(解决方案)

获取相同元素的个数可以使用 array_count_values,这个获取
$a=array('2','1','2');
print_r(array_count_values($a));
?>

得出结果是Array ( [1] => 1 [2] => 2 )

但是要想即只能得到相同个数并想知道下标的,目前想到的就是循环数组然后做比较了

我只写了一个统计相同元素,至于位置的话,去遍历$value!=1的元素就可以了

$array=array("a","b","c","a","c","d","a");function search($ar){	$cnt=count($ar);	$br=array();	for($i=0;$i<$cnt;$i++){		$t=$ar[$i];		//echo $t;		if(!$br[$t]){			$br[$t]=1;		}else{			$br[$t]++;		}	}	return $br;}$cr=search($array);print_r($cr);

Array ( [a] => 3 [b] => 1 [c] => 2 [d] => 1 ) 

$a = array('2','1','2');$xt = array_diff(array_count_values($a), array(1));print_r($xt);foreach(array_keys($xt) as $v) {  echo $v, ': ', join(',', array_keys(array_filter($a, function($c) use ($v) { return $c == $v; })));}

Array
(
    [2] => 2
)
2: 0,2

这么晚了,感谢LS几位的帮忙哈,谢谢了

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