Say I have a long(ish) variable, $row['data']['manybullets']['bullets']['bullet'][0]
, and want to test whether it's set using the ternary operator:
$bulletx =
isset($row['data']['property']['bullets']['bullet'][0]) // condition
? $row['data']['property']['bullets']['bullet'][0] // true
: 'empty'; // false
Is there anyway for me to reference the subject of the expression rather than repeating it. E.g.
$bulletx =
isset($row['data']['property']['bullets']['bullet'][0]) // condition
? SUBJECT // true
: 'empty'; // false
Curious.
PHP supports foo ?: bar
but unfortunately this won't work because of the isset()
in your condition.
So unfortunately there is no really good way to do this in a shorter way. Besides using another language of course (e.g. foo.get(..., 'empty')
in python)
However, if the default value being evaluated in any case is not a problem (e.g. because it's just a static value anyway) you can use a function:
function ifsetor(&$value, $default) {
return isset($value) ? $value : $default;
}
Because of the reference argument this will not throw an E_NOTICE in case of an undefined value.
You can do it like this:
$bulletx = ($r=$row['data']['property']['bullets']['bullet'][0]) ? $r : 'empty';
See working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With