开发者

Short if-else logic

Why this

$count = 0;
   echo $count === 0
    ? 'zero'
   开发者_StackOverflow : $count === 1
     ? 'one'
     : 'more';

echoes 1? Shouldn't it echo zero?


utilize parenthesis!

echo ($count === 0 ? 'zero' :($count === 1 ? 'one': 'more') );

The reason why your version echoes 'one' is because php thinks the 1st ? is part of the statement therefore if $count is equal to zero do the last possible thing (last ?) which is 'one'

read up on this


While this is a pretty short list of values, you could alternatively use a map:

$map = array("zero", "one", "more");
echo $map[min($count,2)];     // trick: 2 becomes max value via min()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜