检查数组中变量是否存在多次? [英] Check if variable exist more than once in array?
问题描述
我想在PHP中执行if / else语句,依赖于数组中的一个项目不止一次存在。你可以在in_array中使用count吗?做一些像
I want to do an if/else statement in PHP that relies on an item in the array existing more than once or not. Can you use count in in_array? to do something like:
if(count(in_array($ itemno_array)))> 1 {
EXECUTE CODE}
推荐答案
让$ item成为频率为正在检查数组,$ array是要搜索的数组。
Let $item be the item whose frequency you are checking for in the array, $array be the array you are searching in.
解决方案1:
$array_count = array_count_values($array);
if (array_key_exists($item, $array_count) && ($array_count["$item"] > 1))
{
/* Execute code */
}
array_count_values()返回一个数组,使用输入数组的值作为键及其频率输入值( http://php.net/manual/en/function .array-count-values.php )
array_count_values() returns an array using the values of the input array as keys and their frequency in input as values (http://php.net/manual/en/function.array-count-values.php)
解决方案2:
if (count(array_keys($array, $item)) > 1)
{
/* Execute code */
}
检查这个 http://www.php.net/manual/en/function.array-keys.php - 如果指定了可选的search_value,则只返回该值的键
Check this http://www.php.net/manual/en/function.array-keys.php - "If the optional search_value is specified, then only the keys for that value are returned"
这篇关于检查数组中变量是否存在多次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!