簡體   English   中英

為什么PHP函數找不到in_array項目?

[英]Why PHP function can't find item in_array?

我用Google搜索和搜索StackOverflow多次,以閱讀整個PHP手冊中的in_array()但仍然堅持我認為這將是一個非常簡單的任務。

所以我的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)只是為了檢查它是否可以讀取數組,並且它確實將整個數組返回給我(這意味着函數到達了外部數組),但是每次都對in_array()否。

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()會告訴您是否設置了數組的索引,並且其值不為null
  • array_key_exists()將明確告訴您索引是否存在於數組中,即使該值是否為null

觀看此現場演示

話雖如此, 不鼓勵使用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);

請參閱是否將PHP中的全局變量視為不良做法? 如果是這樣,為什么?

您不能將in_array()函數用於多維數組。 相反,您可以使用array_key_exists()來檢查密鑰是否存在。

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

index只是$pages_access數組中的 in_array檢查值。 要修復您的代碼:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM