为什么 PHP 函数找不到项目 in_array?

Why PHP function can't find item in_array?

我在 Whosebug 上搜索和搜索了很多次,并阅读了 in_array() 的整个 PHP 手册,但仍然坚持我认为这将是一项非常简单的任务。

所以我的 config.php 文件中有这个数组:

$page_access = array(
    'index' => array('1', '2', '3'),
    'users' => array('4', '5', '6')
);

在 functions.php 我有:

include 'config.php';

function level_access($page){
    global $page_access;
    if(in_array($page, $page_access)){
        echo "yes";
    } else {
        echo "no";
    }
}

level_access('index');

我希望得到 "yes" 作为输出,因为那时我会在函数中做其他事情,但无论我做什么,我都坚持使用 "no" 输出。

我已经在函数内部尝试了 print_r($page_access) 只是为了检查它是否可以读取数组,它确实 return 我整个数组(这意味着函数正在到达外部数组) , 但每次 in_array() 的答案都是 NO.

index 只是 $pages_access 数组中的一个 keyin_array 检查值。 要修复您的代码:

function level_access($page){
    global $page_access;
    if(in_array($page, array_keys($page_access))){
        echo "yes";
    } else {
        echo "no";
    }
}

index 是子数组的键,而不是它的值 in_array() 将在数组中查找它的值,而不是它的索引。

您可以改用 array_key_exists()isset()。使用 isset() 时,检查是否设置了数组索引。

if (array_key_exists($page, $page_access)) {
    echo "yes";
}

// Or..

if (isset($page_access[$page])) {
    echo "yes";
}
  • isset()会告诉你是否设置了数组的索引,它的值不为空
  • array_key_exists() 会明确告诉你索引是否存在于数组中,即使该值是否为 null

看到这个live demo

也就是说,global 关键字的使用是 劝阻,您应该将变量作为参数传递给函数。

$page_access = array(
    'index' => array('1', '2', '3'),
    'users' => array('4', '5', '6')
);

function level_access($page, $page_access) {
    // Either isset() or array_key_exists() will do - read their docs for more info
    // if (array_key_exists($page, $page_access)) {
    if (isset($page_access[$page])) {
        echo "yes";
    } else {
        echo "no";
    }
}
level_access($page, $page_access);

Are global variables in PHP considered bad practice? If so, why?

您正在使用 in_array() 搜索值,您不能使用它。 而是使用 array_key_exists().

您不能对多维数组使用 in_array() 函数。 相反,您可以使用 array_key_exists() 检查密钥是否存在。

function level_access($page)
{
    global $page_access;
    if (array_key_exists($page, $page_access)) {
        echo "yes";
    } else {
        echo "no";
    }
}