Question

I use the ternary operator quite often but I've not been able to find anything in the documentation about this and I've always wondered it.

The following is a possible example:

echo ($something->message ? $something->message : 'no message');

as you can see, if $something->message is correct, we return $something->message, but why write it twice? Is there a way to do something like:

echo ($something->message ? this : 'no message');

Now I'm not well versed in programming theory, so it's possible that there is a reason that the former cannot be referenced with something like "this" but why not? Would this not stream line the use of the ternary operator? For something like my example it's pretty useless, but let's say it's

echo (function(another_function($variable)) ? function(another_function($variable)) : 'false');

I'm unable to find any way to do this, so I'm assuming it's not possible, if I'm wrong please inform me, otherwise: why not? Why is this not possible, what's the technical reason, or is it just something that never happened? Should I be declaring it as a variable and then testing against that variable?

Was it helpful?

Solution

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Source

For example

$used_value = function1() ?: $default_value;

Is the same as

$check_value = function1(); //doesn't re-evaluate function1()
if( $check_value ) {
    $used_value = $check_value;
} else {
    $used_value = $default_value;
}

Word for the wise

If your going to be depending on typecasting to TRUE it's important to understand what WILL typecast to TRUE and what won't. It's probably worth brushing up on PHP's type juggling and reading the type conversion tables. For example (bool)array() is FALSE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top