无法理解in_array()

时间:2012-06-11 16:40:14

标签: php arrays

<?php
$whitelist = array('contact', 'about', 'user');
$_GET['page'] = array('contact');
$test = $_GET['page'];
if(isset($test))
{
  if(in_array($whitelist, $test))
  {
    $got = $test;
    echo $got;
  }
  else 
  {
    $got = 'home';
    echo $got;  
  }
}
?>

现在,我应该将结果视为“联系”,但我正在'回家'。那是为什么?

3 个答案:

答案 0 :(得分:3)

in_array第一个参数应该是针(意思是:你在寻找什么),第二个应该是haystack(意思是:我们在寻找的地方)。

我认为你颠倒了那些,以及needl应该是字符串(或其他变量类型),但不是数组。

所以你的脚本应该是这样的:

<?php
$whitelist = array('contact', 'about', 'user');
$test = 'contact';
if(isset($test))
{
  if(in_array($test, $whitelist))
  {
    $got = $test;
    echo $got;
  }
  else 
  {
    $got = 'home';
    echo $got;  
  }
}
?>

答案 1 :(得分:3)

因为白名单是一个字符串数组,$ _GET ['page']是一个数组,而不是一个字符串。而且你的参数也是错误的。

答案 2 :(得分:0)

<?php
$whitelist = array('contact', 'about', 'user');
$_GET['page'] = 'contact';
$test = $_GET['page'];
if(isset($test))
{
  if(in_array($test, $whitelist))
  {
    $got = $test;
    echo $got;
  }
  else 
  {
    $got = 'home';
    echo $got;  
  }
}
?>
相关问题