php - 有没有一种惯用的方法可以从 PHP 中的数组中获取可能未定义的键?

标签 php arrays idioms

PH人民,我已经厌倦了这样做

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

或者这个

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

不要让任何人告诉我去做

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

我得了支气管炎。没人有时间去他妈的。


我想我可以做一个函数...

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

但这是最好的(最惯用的)方式吗?

最佳答案

更优雅的方式:

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

现在你可以这样做:

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

等这里 $value 是通过引用传递的,所以它不会抛出通知。

进一步阅读:

关于php - 有没有一种惯用的方法可以从 PHP 中的数组中获取可能未定义的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502348/

相关文章:

php - Google PHP API 文件太多

c - 为什么 0 是我动态创建的数组的最后一个值的一个非常常见的整数?

java - java中最大和第二大的数从整数数组中获得相同的值?

"foo.nil? ? nil : foo.to_i"的 Ruby 习语?

php - MS SQL try catch 在被 php mssql_query 执行时被忽略

php - 最佳实践ajax随机加载更多图像(内容)

php - 为什么游标 CSS 在 Gmail 中不起作用?

c++ - 一种不使用 if 语句评估阈值的方法

用于测试命令是否存在的 PowerShell 习语?

objective-c - 从 [[class alloc] init] 返回 nil 的后续操作