Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

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."

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