If you're using PHP 7+, you have the null-coalesce operator (??
) to compact the expression:
($pricing ?? '') === 'price' and print 'selected="true"';
Try it online at 3v4l.org.
Let's break that down:
($pricing ?? '')
gracefully handles the scenario where $pricing
has not been defined. If defined, this expression returns the defined value of $pricing
: otherwise, it returns the empty string ''
.
=== 'price'
compares the now-defined value against exactly the value we are looking for. You can extend this test, of course. Like, if you had a set of defined values, you could instead use an in_array
check.
and print 'selected="true"'
reacts to the boolean result of the prior test, printing the desired value in the case of a match. Since outputting an empty string is equivalent to no output at all, we can simply use the and
logical operator to conditionally output. Note that echo
cannot be used here, as it's a language construct. Instead use print
, printf
, var_dump
, etc.
That said, the emerging idiom for defaulting a potentially-undefined value uses the null-coalesce operator like:
$pricing = ($pricing ?? '');
I suggest defaulting in this way, versus the inline check given above, because it ensures $pricing
is defined from that spot on. Said another way, don't litter your code with ($pricing ?? '') === 'price'
checks: just do it once and be done with it.
As an aside, if you wanted to do multiple things on this condition, you could use an anonymous on-call:
($pricing ?? '') === 'price' and (function() {
echo 'this';
echo 'that';
})();
But I would not recommend these gymnastics.