PHP Simplify a ternary operation

心已入冬 提交于 2019-12-12 19:31:02

问题


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.


回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/3034338/php-simplify-a-ternary-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!