Assuming
$method = array('I am','sparticus');
In the statment
$oneMethod = count($methods) <= 1;
The call to count($methods)
always returns an int (see its return type on the count page), In our example that int
is 2
$oneMethod = 2 <= 1;
And then 2 <= 1
resolves to a boolean, because 2
is not less than or equal to 1
.
$oneMethod = false;
In the second example
$oneMethod = (count($methods) <= 1) ? true : false;
Again, we have count($methods)
resolving to an int
.
$oneMethod = (2 <= 1) ? true : false;
And then (2 <= 1)
resolves to a boolean.
$oneMethod = false ? true : false;
And then ternary statment resolves to false
(the first part of the ternary is true
, which means it resolves to the third part after the :
.
Finally, personal opinion, neither form is particularly ideal. The ternary statment is redundant (true ? true : false;
), and while the first form
$oneMethod = count($methods) <= 1;
doesn't have that redundancy, it does look a bit like the bitwise operators, which could potentially cause confusion amoung a certain class of developers. I usually prefer something like this
$oneMethod = true;
if(count($methods) > 1)
{
$oneMethod = false;
}
Slightly more code, but it's hard to mistake that for something else. We can leave the argument about if
style braces to others.
Thanks, I'd much rather have beginner-friendly code before the most terse. Assignments are easier to understand with explicit values rather than implied. A few years ago I would have balked at the ternary too, but I do like the (redundant) clarity and shortness.