0

I have a function within my PHP project which has some specific params..

 $user_sequence = $user['user_sequence'];

 if ($cached || !$user_sequence) {
    return;
 }

Notice: Undefined index: user_sequence

I have fixed that with:

        if (isset($user['user_sequence'])) {                     
           $user_sequence = $user['user_sequence'];     
         }

But now my second if() clause get's a warning:

Variable '$user_sequence' is probably undefined

Would setting it to null before if() be the best approach to solve it? Thanks

  • 2
    Using the null coalescing operator would be a bit more "tidy" perhaps. https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce, https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator – CBroe Mar 24 '22 at 15:00

1 Answers1

0

Spelled out in full, you need to specify what the value should be if $user['user_sequence'] is not set. In your second if statement, you are checking !$user_sequence, so a logical default value would be boolean false:

if (isset($user['user_sequence'])) {                     
   $user_sequence = $user['user_sequence'];
}
else {
   $user_sequence = false;
}

Luckily, PHP doesn't make use write out that whole if statement, because we can use the null coalescing operator, and shorten it to this:

$user_sequence = $user['user_sequence'] ?? false;

In other situations, you might want to default to an empty array ($something ?? []) or even just null ($something ?? null).

IMSoP
  • 89,526
  • 13
  • 117
  • 169