Hello, I am very new to programming and in the following exercise, I don’t know why, from the beginning, true="1"…
Would would this be?
This is the exercise:
$var = true ? “1” : false ? “2” : “3” ;
The solution is 2 (I already calculated it) but I don’t understand why in the start, true=1, Maybe 1 always equivalent to true by principle in programming?
It is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious:
Example #4 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is ‘t’
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? ‘true’ : false) ? ‘t’ : ‘f’);
// here, you can see that the first expression is evaluated to ‘true’, which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>