【问题标题】:Is there an idiomatic way to get a potentially undefined key from an array in PHP?有没有一种惯用的方法可以从 PHP 中的数组中获取可能未定义的键?
【发布时间】:2014-06-23 12:26:23
【问题描述】:

PHPeoples,我厌倦了这样做

$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

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


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

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

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

【问题讨论】:

  • 这对我来说是合理的。我使用相同的技巧来获取具有默认值的 $_POST 或 $_GET 参数。在添加所有噱头之前,您的问题更好。
  • 是的,一个函数调用和 2 个必需的参数将是最少的。
  • 谁在没有评论的情况下否决了这个? RIP
  • 您不会使用“功能”版本节省任何时间/空间。
  • @MarcB,我认为$val = array_get($arr, $key);$val = isset($arr[$key]) ? $arr[$key] : null; 读起来更好。我认为它可以节省时间/空间以及介于两者之间的所有内容。

标签: php arrays idioms


【解决方案1】:

更优雅的做法:

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

现在你可以这样做了:

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

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

进一步阅读:

【讨论】:

    【解决方案2】:

    如果您需要确保某些键存在,那么您可以创建一个默认数组并合并到您的输入(或其他)中。这样一来,所有必要的密钥都会存在,并且会在可能的情况下进行更新:

    $defaults = array(
        'foo' => '',
        'bar' => ''
    );
    
    $data = array_merge($defaults, $someOtherArray);
    

    array_merge() 的文档:http://php.net/array_merge

    在考虑 HTML 表单上的复选框时,我发现这很有帮助,这些复选框可能会或可能不会出现在 $_GET$_POST 中。

    请注意,此过程需要字符串数组键,而不是数字键。有关说明,请参阅文档。

    【讨论】:

    • 我熟悉这种技术,好吧,这对于具有默认值的 assoc 数组来说很好,但并不总是需要定义默认值。此解决方案不适用于我的 $val = $arr[5] 示例。
    • @naomik 有趣的是,你什么时候不知道一段代码需要什么键?
    【解决方案3】:

    不要忘记函数 isset() 不会为对应于 NULL 值的数组键返回 TRUE,而 array_key_exists() 会。所以以上所有答案都不能正确处理数组中的 NULL 元素。对于这种情况,您可以查看我的编辑答案。例如我们有一些数组:

       $test = array(NULL,'',0,false,'0');
    

    如果我们使用(来自本主题上面的答案)函数:

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

    并尝试获取数组数据:

    echo '---------------------';
    var_dump($test);
    echo 'Array count : '.count($test).'<br>';
    echo '---------------------';
    var_dump(ifsetor($test[0], 'Key not exists'));
    var_dump(ifsetor($test[1],'Key not exists'));
    var_dump(ifsetor($test[2],'Key not exists'));
    var_dump(ifsetor($test[3], 'Key not exists'));
    var_dump(ifsetor($test[4],'Key not exists'));
    var_dump(ifsetor($test1[5],'Key not exists'));
    
    function ifsetor(&$value, $default = null) {
        return isset($value) ? $value : $default;
    }
    

    我们的结果是:

    ---------------------
    
    array (size=5)
      0 => null
      1 => string '' (length=0)
      2 => int 0
      3 => boolean false
      4 => string '0' (length=1)
    
    Array count : 5
    ---------------------
    
    string 'Key not exists' (length=9) //But value in this key of array - NULL! and key exists
    
    string '' (length=0)
    
    int 0
    
    boolean false
    
    string '0' (length=1)
    
    string 'Key not exists' (length=9)
    

    所以我们可以一起使用 issetarray_key_exists 来检查它。不要忘记检查这是不是数组;

    echo '---------------------';
    var_dump($test);
    echo 'Array count : '.count($test).'<br>';
    echo '---------------------';
    var_dump(array_get($test, 0, 'Key not exists'));
    var_dump(array_get($test, 1,'Key not exists'));
    var_dump(array_get($test, 2,'Key not exists'));
    var_dump(array_get($test, 3, 'Key not exists'));
    var_dump(array_get($test, 4,'Key not exists'));
    var_dump(array_get($test, 5,'Key not exists')); //Key not exists
    var_dump(array_get($test1, 5,'Key not exists')); //This is not array
    
    
    function array_get($arr, $key, $default=null) {
      if(is_array($arr)){
        return  isset($arr[$key]) || array_key_exists($key, $arr)
            ? $arr[$key]
            : $default;
      }else{
        return 'No array given';
      }
    
    }
    

    现在答案是正确的:

    ---------------------
    
    array (size=5)
      0 => null
      1 => string '' (length=0)
      2 => int 0
      3 => boolean false
      4 => string '0' (length=1)
    
    Array count : 5
    ---------------------
    
    null  //Perfect - key exists!
    
    string '' (length=0)
    
    int 0
    
    boolean false
    
    string '0' (length=1)
    
    string 'No array given' (length=14)
    
    string 'Key not exists' (length=14)
    

    【讨论】:

    • 我没有对此投反对票,但您需要使用return isset($value) ?... 而不是return $value ?...
    • @naomik 为什么我们需要使用 isset?请解释?我们用 '?' - 表达式 (expr1) ? (expr2) : (expr3) 如果 expr1 计算结果为 TRUE,则计算结果为 expr2,如果 expr1 计算结果为 FALSE,则计算 expr3
    • 如果 $value 评估为“假”值(0false''),您的函数将返回 null
    • 我编辑我的答案并为数组和 NULL 值添加检查键。请检查并回答我的解决方案)
    【解决方案4】:

    如果使用$_GET$_POST$_COOKIE$_SERVER$_ENV,它已经是一个内置函数,你可以使用:

    $value = filter_input(INPUT_GET, $key);
    

    此外,它还有更多功能。如果您还想在同一作业中验证或清理过滤器,可选过滤器会很方便。

    返回 - 成功时请求变量的值,如果过滤器失败则返回 FALSE, 如果未设置 variable_name 变量,则为 NULL。如果国旗 使用 FILTER_NULL_ON_FAILURE,如果变量是则返回 FALSE 如果过滤器失败,则未设置和 NULL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2011-01-15
      • 2012-04-09
      • 1970-01-01
      • 2017-07-05
      相关资源
      最近更新 更多