Question

In PHP, if I have a ternary like this:

$my_thing = $this->myAttribute ? $this->myAttribute : "No attribute was set.";

can it be abbreviated like this?

$my_thing = $this->myAttribute ?: "No attribute was set."

I thought I remembered PHP supporting this in its ternaries, but now I'm getting an error.

Was it helpful?

Solution

It's supported in PHP 5.3 and up. From PHP.net

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.

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