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()
精彩评论