user370306
user370306

Reputation:

Short if-else logic

Why this

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

echoes 1? Shouldn't it echo zero?

Upvotes: 0

Views: 192

Answers (2)

mario
mario

Reputation: 145492

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()

Upvotes: 0

Naftali
Naftali

Reputation: 146310

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

Upvotes: 2

Related Questions