I dont understand how that output (“four“) comes?
$a = 2;
echo
$a == 1 ? 'one' :
$a == 2 ? 'two' :
$a == 3 ? 'three' :
$a == 5 ? 'four' :
'other'
;
// prints 'four'
I don’t understand why “four” gets printed.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You need to bracket the ternary conditionals:
returns:
as you’d expect.
See the note at the bottom of “Ternary operators” at PHP Ternary operator help.
The expressions are being evaluated left to right. So you are actually getting:
So for
$a=2, you get:and then
and then
and then
and so
echo 'four'.Remember that PHP is dynamically typed and treats any non-zero non-null values as TRUE.