简体   繁体   English

搜索数组以查找关键的PHP

[英]search array for key PHP

function returnStatus($status)
{
    $supportStatus = [
        0 => 'open',
        1 =>'half closed',
        9 => 'closed',
    ];

    $key = array_search($status, $supportStatus);
    return $supportStatus[$key];
}

My script returns 0 (open), even if I sent 9 as int to the function. 即使我将9作为int发送给函数,我的脚本也会返回0(打开)。

What you are looking for is the array_key_exists() 您正在寻找的是array_key_exists()

function returnStatus($status){

    $supportStatus = [
        0 => 'open',
        1 =>'half closed',
        9 => 'closed',
    ];

    $key = array_key_exists($status, $supportStatus);
    return $supportStatus[$key];
}

Furthermore you donot even need to do that jugglery, if eventually you are interested in the value stored in that key's location. 此外,你甚至DONOT需要做的把戏,如果最终你有兴趣存储在该关键位置的值。

I'd just do it in one line as below.. 我只需要一行就可以了,如下所示。

echo isset($supportStatus[$status]) ? $supportStatus[$status]: false;

or with assignment operator 或与赋值运算符

$output = isset($supportStatus[$status]) ? $supportStatus[$status]: '';

I hope this is what you're looking for, 希望这就是您要的东西,

function searchColor($color){
    $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
    $key = array_search($color, $array); 
    return $array[$key];    
}
echo searchColor('blue');

Update your code and see if it works, here is the reference . 更新您的代码,看看它是否有效, 这是参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM