skip to Main Content

Often I’m using ?? to check variables, but that will pass the left variable even if empty.

I want to express

(!empty($b)) ? $b : $c

Close is:

$b ?: $c

Except that will throw a warning if $b is not set.

$b ?? $c

is the equivalent to isset(), not empty() so if $b is "" that’ll be returned.

I’m sure I’m missing something.

I guess want I want is @$b ?: $c which would express $b as long as it’s set and not empty(), otherwise $c, but @ to hide warnings is such bad form

2

Answers


  1. Try the following:

    ($b ?? '') ?: $c

    I compared its behavior to (!empty($b)) ? $b : $c, and they seem to be equivalent.

    Tested using onlinephp.io

    Login or Signup to reply.
  2. OK, as you can see in the comments, I think that you want to use a single operator/function to select an alternative value when when a variable is empty.

    I suggest a custom function for this:

    function neverEmpty(&$firstChoice, $alternative) {
        return empty($firstChoice) ? $alternative : $firstChoice;
    }
    

    See: https://3v4l.org/743sc

    I think it is obvious what it does. The ampersant before the first function argument means that this argument is passed by reference.

    With thanks to mickmackusa for correcting a bug. He also suggested, and I agree, that we shouldn’t try to write the shortest possible code. Code needs to be readable, understandable, and maintainable. A custom function isn’t all that much slower than a build-in function. You really cannot tell the difference once you have an application that, for instance, uses a database.

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