Logo Questions Linux Laravel Mysql Ubuntu Git Menu

php ternary operator giving an error

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.

like image 249
Don P Avatar asked Mar 24 '23 09:03

Don P

1 Answers

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.

like image 103
AlliterativeAlice Avatar answered Apr 02 '23 17:04