php 如果键在变量中,PHP如何从数组中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2281526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:51:31  来源:igfitidea点击:

PHP how to get value from array if key is in a variable

phparrays

提问by Mazatec

I have a key stored in a variable like so:

我有一个存储在变量中的密钥,如下所示:

$key = 4;

I tried to get the relevant value like so:

我试图像这样获得相关的价值:

$value = $array[$key];

but it failed. Help.

但它失败了。帮助。

回答by Sarfraz

Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your arrayeg:

您的代码似乎没问题,请确保您指定的键确实存在于数组中,或者此类键在您的数组中具有值,例如:

$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);

Output:

输出:

Array
(
    [0] => 4
)

Now:

现在:

$key = 4;
$value = $array[$key];
print $value;

Output:

输出:

Hello There

回答by code_burgar

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

回答by sab0t

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

正如其他人所说,它可能会失败,因为数组中不存在请求的键。我在这里有一个辅助函数,它接受数组、可疑的键,以及在键不存在的情况下的默认返回。

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

希望能帮助到你。

回答by Gumbo

It should work the way you intended.

它应该按照您的预期工作。

$array = array('value-0', 'value-1', 'value-2', 'value-3', 'value-4', 'value-5' /* … */);
$key = 4;
$value = $array[$key];
echo $value; // value-4

But maybe there is no element with the key 4. If you want to get the fiveth item no matter what key it has, you can use array_slice:

但也许 key 没有元素4。如果你想得到第五个项目,不管它有什么键,你可以使用array_slice

$value = array_slice($array, 4, 1);