1个包含2个或更多相等元素PHP的数组

时间:2013-06-08 10:35:26

标签: php html

关于比较具有相同值的2个数组或检查数组中的值是否存在有很多问题,但我无法在任何地方找到此问题:

如何在一个阵列中检查某个变量/值是否存在两次或更多?

例如:

$array_to_check = array( "this", "this" , "yes" , "no" , "maybe" , "yes" , "yes" );

$this_value = "this";

// how to check if $this_value or 'this' value exist more than twice in $array_to_check array:
// if it exist more than twice, echo yes it exist more than once!!

看看是否有一个可以调用的函数也很好,我可以在其中插入变量进行检查,并将数组作为参数进行检查,如果变量值在数组中存在两次以上则返回true

例如:

$function check_if_more_than_two($the_variable_to_check, $array_to_check)
非常感谢你。任何帮助将不胜感激:))

4 个答案:

答案 0 :(得分:4)

array_keys函数有一个搜索工具

您所要做的就是计算结果数量

count(array_keys($array_to_check, $this_value));

答案 1 :(得分:2)

借用@ pvnarula的回答,但改善了表现:

function array_has_dupes($array) {
    return count($array) !== count(array_flip($array));
}

array_flip具有“折叠”重复值的便利效果,但无需检查它是否与所有其他值相等。与数组如何保存,访问等有关。请注意,这只适用于字符串和/或数字的数组,而不适用于嵌套数组或更复杂的数组。

效果统计:

  • array_unique:2.38407087326中的1,000,000次迭代
  • array_flip:1.63431406021s中的1,000,000次迭代

编辑:重新阅读问题,我意识到这不是要求的!但是,知道它仍然很有用,所以我会留在那里。

至于实际回答问题,{​​{3}}是最好的选择,计算返回的数组并检查它是否至少有2个项目:

function array_has_dupes($array,$value) {
    return count(array_keys($array,$value)) > 1;
}

答案 2 :(得分:1)

function check_if_more_than_two($the_variable_to_check, $array_to_check) {
  $values_array= array_count_values($array_to_check);
  if ($values_array[$the_variable_to_check] > 2 ) {
    return true;
  } else {
    return false;
  }
}

答案 3 :(得分:1)

使用php函数array_keys。获得所需的输出。

$array_to_check = array( "this", "this" , "yes" , "no" , "maybe" , "yes" , "yes" );

$this_value = "this";

if (count(array_keys($array_to_check, $this_value)) > 2) {

     echo "Yes";
}
相关问题