将变量与多个数组匹配

时间:2012-10-23 17:26:29

标签: php arrays preg-match

假设我有随机的$ variable和三个数组:

$array1 = ("one", "two", "three");
$array2 = ("four", "five", "six");
$array3 = ("seven", "eight", "nine");

如何做到这一点:

if $variable is in $array1
echo "in array one";
elseif $variable is $array2
echo "in array two";
elseif $variable is in $array3
echo "in array three";
else
echo "variable isnt in any of arrays";

我希望你明白这一点,我真的很感激任何帮助,我考虑逐个数组中的项目,然后preg_matching它们..但我不知道如何使用多个数组:)< / p>

2 个答案:

答案 0 :(得分:1)

您可以使用in_array()功能。 [Doc]

您的代码如下:

if (in_array ($variable, $array1)) {
 echo "in array 1";
} else if(in_array ($variable, $array2)) {
 echo "in array 2";
} [...] else {
 echo "isnt in any";
}

答案 1 :(得分:0)

您需要使用in_array,请参阅手册here

  if (in_array($variable, $array1))
   echo "in array one";
  else if (in_array($variable, $array2))
    echo "in array two";
  else if (in_array($variable, $array3))
    echo "in array three";
  else
    echo "variable isnt in any of arrays";