skip to Main Content

I’m getting the error "Undefined array key "name" in the following code:

if ($arr & $arr['name']??'')

Shouldn’t the null coalescing operator prevent that error if the array key doesn’t exist??

I tried using isset() instead and it did not return an error. But what gives?

I’ve used the null coalescing operator loads before and never had any problems with it. I don’t understand what is different about this code?

2

Answers


  1. The null coalesce operator does not produce a warning/error.

    As stated in https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce, the coalesce is identical to using isset(). You have a & instead of && in the code.

    <?php
    // Example usage for: Null Coalesce Operator
    $action = $_POST['action'] ?? 'default';
    
    // The above is identical to this if/else statement
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
    } else {
        $action = 'default';
    }
    ?>
    
    Login or Signup to reply.
  2. Regardless of the use of & versus &&, those operators have a higher precedence than the ?? operator. So this:

    if ($arr && $arr['name'] ?? '')
    

    Evaluates to this:

    if (($arr && $arr['name']) ?? '')
    

    Which means PHP tries first to evaluate $arr['name'] outside the context of the null coalesce, so you get the notice. You can force the desired precedence with explicit parens:

    if ($arr && ($arr['name'] ?? ''))
    

    That said, the explicit check for $arr is generally not needed when you use null coalesce, so what you probably want is simply:

    if ($arr['name'] ?? '')
    

    Which basically means, "if a value is present and not empty."

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search