PHP shorthand for combination of ?? and ?: operators?

89 Views Asked by At

is there any "beautiful" shorthand in PHP to use ?? and ?: operators together?

I often check something for array keys to exist and to "evalutate to TRUE" in web apps, e.g. for ids, such as

if ($foo['id']) {
    // ...
}

but this leads to PHP notices starting with PHP 8.x+.

I could write

if (isset($foo['id']) && $foo['id']) {
    // ...
}

but this makes the code such unreadable.

An alternative would be

if ($foo['id'] ?? NULL) {
    // ...
}

but also this is ...cruel.

Especially when writing something like

echo 'Rsource foo '.(($foo['id'] ?? NULL) ? 'edit' : 'create');

Any ideas, recommendations?

1

There are 1 best solutions below

0
deceze On

array keys to exist and to "evalutate to TRUE"

That's empty, or rather, !empty:

if (!empty($foo['id']))