是否有一个地道的方式来获得在PHP数组潜在不确定的钥匙吗? [英] Is there an idiomatic way to get a potentially undefined key from an array in PHP?

查看:122
本文介绍了是否有一个地道的方式来获得在PHP数组潜在不确定的钥匙吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHPeoples,我太累了这样做的。

PHPeoples, I'm so tired of doing this

$value = isset($arr[$key]) ? $arr[$key] : null;

或者这

$value = array_key_exists($key, $arr) ? $arr[$key] : null;


不要没人告诉我该怎么


Don't nobody tell me to do

$arr   = array(1);
$key   = 5;
$value = $arr[$key];
// Notice: Undefined offset: 5

我有支气管炎。没人有时间f'dat。

I got bronchitis. Ain't nobody got time f'dat.

我可以做一个功能,我想...

I could make a function, I guess...

function array_get(Array $arr, $key, $default=null) {
  return array_key_exists($key, $arr)
    ? $arr[$key]
    : $default
  ;
}

但是,这是最好的(最地道)的方式?

But is this the best (most idiomatic) way?

推荐答案

做的更优雅的方式:

function ifsetor(&$value, $default = null) {
    return isset($value) ? $value : $default;
}

现在你可以这样做:

$value   = ifsetor($arr[$key]);
$message = ifsetor($_POST['message'], 'No message posted');

等。在这里, $值按引用传递,所以它不会抛出一个通知。

etc. Here $value is passed by reference, so it wouldn't throw a Notice.

延伸阅读:

  • NikiC's blog — The case against the ifsetor function
  • PHP RFC — https://wiki.php.net/rfc/ifsetor

这篇关于是否有一个地道的方式来获得在PHP数组潜在不确定的钥匙吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆