Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Simplify a ternary operation

In PHP, is there a way to simplify this even more, without using an if()?

$foo = $bar!==0 ? $foo : '';

I was wondering if there was a way to not reassign $foo to itself if the condition is satisfied. I understand there is a way to do this in Javascript (using &&, right?), but was wondering if there was a way to do this in PHP.

like image 957
Obay Avatar asked Sep 14 '26 05:09

Obay


2 Answers

In PHP 5.3 the short form of the ternary operator has finally arrived, so you can do the following.

$foo = $bar ?: '';

See the Comparison Operators section - "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 190
El Yobo Avatar answered Sep 16 '26 20:09

El Yobo


Yup, you can use the logical and (&&) operator in PHP as well.

$bar === 0 && $foo = '';

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!