如何检查数组是否多次具有值 [英] How to check if an array has a value multiple times

查看:58
本文介绍了如何检查数组是否多次具有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看数组是否多次具有相同的值,例如:

I want to see if an array has the same value multiple times,example:

$array=array('val1','val2','val3','val1');

如您所见,在上面的数组中,有2 x val1.要搜索数组是否包含值,我可以使用in_array来做到这一点:

As you can see,in the array above, there are 2 x val1 . To search if an array contains a value,i can do it with in_array:

$search=in_array('val1',$array);

它将返回true,因为val1存在于数组中,但是如果多次发现该值,我需要返回true.

And it will return true because val1 exists in array,but i need to return true if the value is found multiple times.

推荐答案

您可以利用 array_keys()鲜为人知的功能,该功能用于将数组的键作为新数组返回(即没有值.)

You can exploit a lesser known feature of array_keys(), which is used to return the keys of an array as a new array (i.e. without values.)

它接受可选的第二个参数 search ,该参数允许您规定只希望返回值与您的搜索相对应的那些键.所以:

It accepts an optional second parameter, search, that allows you to stipulate that you wish to have only those keys returned whose value corresponds to your search. So:

$arr = array('one', 'two', 'one', 'three');
$indexes = array_keys($arr, 'one'); //array(0, 2)

这篇关于如何检查数组是否多次具有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆