views:

85

answers:

2

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.

+4  A: 

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

$bar === 0 && $foo = '';
Tim Cooper
Do you have any documentation/tutorials on this method? I've seen it used but never fully understood it.
Kerry
deceze
Wow, great explanation, thanks :)
Kerry
+2  A: 

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

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

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

El Yobo