phplaravelcontrollerhelperundefined-index

Undefined Index - isset guard doesn't work with helper


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

Solution

  • 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