【问题标题】:Comparing 1 value to single array in PHP将 1 个值与 PHP 中的单个数组进行比较
【发布时间】:2012-08-06 06:59:59
【问题描述】:

如何将一个值与特定数组中的每个值进行比较?

例如:

$list =  ("blue", "red", "green", "yellow", "orange", "white");
$value = "blue";

if ($value == $list)
{
  // then print "This is BLUE";
}

我只需要一次确定颜色,不需要重复打印其他颜色。

这可能会让我实现从数据库中检索的动态值,然后比较 PHP 脚本中的 [hardcode] 数组。然后,将精确匹配的值返回到屏幕上,例如上面的场景。

【问题讨论】:

    标签: php arrays comparison string-comparison comparison-operators


    【解决方案1】:

    in_array 是在将单个值与数组进行比较时应该使用的函数, 但是如果您需要将多个值与一个数组进行比较,您可以创建一个包含已有值的新数组,然后使用array_intersect($array1,$array2)

    【讨论】:

      【解决方案2】:
      $list = array("blue","orange","green");
      $value = "blue";
      
      if(in_array($value, $list)) {
          echo $value;
      }
      

      【讨论】:

        【解决方案3】:

        你的意思是in_array

        $list =  array("blue", "red", "green", "yellow", "orange", "white");
        $value = "blue";
        
        if (in_array($value, $list))
        {
          // then print "This is BLUE";
        }
        

        【讨论】:

          【解决方案4】:

          你能找到in_array()吗?

          if (in_array('blue', $colors)) {
              // the color blue is there
          }
          

          【讨论】:

          • 这是一个没有例子的惊人答案。每个开发人员,尤其是新手,都应该知道文档在哪里以及如何阅读。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-23
          • 1970-01-01
          • 1970-01-01
          • 2019-04-06
          • 2015-10-17
          相关资源
          最近更新 更多