确定变量是否等于php中数组中的任何变量

时间:2017-09-15 22:13:11

标签: php

有没有办法确定一个变量是否等于数组中任何变量的值? 例如,

IF ($a == $b) {
 echo "there is a match";
}
//where $b is an array of values
//and $a is just a single value

5 个答案:

答案 0 :(得分:6)

Sure there is.

if (in_array($a, $b)) {
    echo "there is a match";
}

如果变量$a类型需要与$b中的值类型相匹配,则应使用严格比较以确保您不会获得

之类的误报
in_array(0, ['abc', '', 42]) // returns true because 0 == ''

通过将in_array的第三个参数设置为true来实现。

in_array(0, ['abc', '', 42], true)  // returns false because 0 !== ''

答案 1 :(得分:1)

您可以使用in_array function

检查数组中是否存在该值
in_array('a', array('a', 'b')); // true
in_array('a', array('b', 'c')); // false

答案 2 :(得分:1)

$b = array("Mac", "NT", "Irix", "Linux");
$a = "single string"
if (in_array($a, $b)) {
    echo "Yes single string is in array";
}

这是php手册中的描述:http://php.net/manual/en/function.in-array.php

答案 3 :(得分:1)

试试这个:

$a = '10';
$b = ['1', 24, '10', '20'];
if (in_array($a, $b)){
    print('find');
}

答案 4 :(得分:1)

试试这个

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

if (in_array("Glenn", $people))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>

https://www.w3schools.com/php/func_array_in_array.asp