Forum Moderators: coopster

Message Too Old, No Replies

Shortcut for falsy expression

         

csdude55

7:33 am on Dec 31, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a common area where I'm looking at non-null (but empty) results from MySQL, and when that happens I need to fall back to a default.

This doesn't work, because it's not null:

$img ?= $imgTwo ? 'default.gif';

This does work, though:

$img = $img ?: $imgTwo ?: 'default.gif';

Is there a way to shorten that second one so that $img isn't listed twice? I know that this doesn't work, but something like it:

$img ?:= $imgTwo ?: 'default.gif';

mack

6:32 pm on Jan 23, 2023 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



I might be misunderstanding, but what I tend to do is set a default value at the start of the script...
$thing="default";

Then as the script progresses I can check if it has been altered using an if clause...

if ($thing != "default")
{
//default value has been overwritten by the script. Get the value and do something with it. Else ignore it.
}

Mack.

ronin

11:06 am on Feb 1, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In certain contexts, I do like super-concise operators like:

  • ? : (ternary operator shorthand)
  • ? ? (null coalescing operator)
  • ? ? = (null coalescing assignment operator)

    But you're right, there isn't a ternary operator shorthand assignment operator (?:=) and, I agree, that would be useful.

    I don't know if it makes much of a difference, but you could use something like:


    (boolval($img)) ?: $img = ($imgTwo ?: 'default.gif');
  • csdude55

    6:35 pm on Feb 1, 2023 (gmt 0)

    WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



    Thanks for the input! I tried a few different versions, and it looks like ?? is the fastest:

    // 2.2482872009277
    if (!isset($img))
    $img = $imgTwo;

    if (!isset($img))
    $img = 'default.gif';

    // 2.6202201843262
    // I also get warnings if $img and $imgTwo aren't defined, but using ? throws an error so I'm
    // not sure what the best solution is there
    (boolval($img)) ?: $img = ($imgTwo ?: 'default.gif');

    // 1.5783309936523
    $img = $img ? $imgTwo ? 'default.gif';


    I usually try to avoid reading the same variable multiple times for the sake of speed, but I guess there's not an alternative in this case :-/