duancan1950 2018-04-20 07:51
浏览 98
已采纳

未定义的索引 - isset guard不适用于帮助程序

I have a multi-dimensional array coming from post request. It looks like this: $request['bags'][1]['fruits']. Sometimes, this value doesn't exist so it returns Undefined Index error.

$model->fruits = $request['bags'][1]['fruits'];

If I use an isset guard in my controller, it works:

$model->fruits = isset($request['bags'][1]['fruits'];) ? $request['bags'][1]['fruits'] : '';
$model->save();

Now, I wanted to wrap this in a function, so that I can use something like nullable($fruits) to make this work.


Now, I tried to wrap this inside a helper method; so I created Helper.php and added this method inside:

function nullable($value) {
    return (isset($value)) ? $value : '';
}

But in my controller, when I call nullable(), it throws Undefined Index error.

nullable($request['bags'][1]['fruits']); // Undefined Index

isset($request['bags'][1]['fruits']) ? $request['bags'][1]['fruits'] : ''; // works
  • 写回答

2条回答 默认 最新

  • dpnof28482 2018-04-20 07:59
    关注

    The problem you encounter is, that the Undefined Index Notice is thrown as soon as the undefined index is requested. This happens as soon as you want to access the value behind the key upon calling your helper function with nullable($request['bags'][1]['fruits']). The value is extracted and then send to the function.

    What you can do instead, is using the null coalesce operator ?? in PHP.

    $model->fruits = $request['bags'][1]['fruits'] ?? '';
    

    If you really want to create your own helper function though, you need to do it in a way, in wich the field is not accessed when the parameters are transfered to the function.

    This can be accomplished by spearating the array from the keys you want to access.

    function nullable(array $array, ...$keys) {
        $current = $array;
        foreach($keys as $key) {
            if (!isset($current[$key])) {
                return NULL;
            }
            $current = $current[$key];
        }
        return $current;
    }
    

    A call would then be nullable($request, 'bags', 1, 'fruits');

    Code example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line