Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator shorthand to use subject of expression in true/false clause rather than repeating

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.

like image 629
Gga Avatar asked Jan 11 '23 21:01

Gga


2 Answers

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.

like image 118
ThiefMaster Avatar answered Jan 14 '23 10:01

ThiefMaster


You can do it like this:

$bulletx = ($r=$row['data']['property']['bullets']['bullet'][0]) ? $r : 'empty';

See working demo

like image 35
Nelson Avatar answered Jan 14 '23 11:01

Nelson