How to fix my PHP inline if using ternary operator?
63,098
Solution 1
Because the precedence of ternary operator ?:
is very low. To fix this, use brackets
echo "...text..." . ($db_field['late']==0 ? ' ' : $db_field['late']) . "...more text...";
Solution 2
echo "...text..." . ( $db_field['late']==0 ? ' ' : $db_field['late'] ) . "...more text...";
Author by
Graeme
Updated on February 08, 2022Comments
-
Graeme about 2 years
I saw an example in the PHP Manual:
<?php $var = TRUE; echo $var==TRUE ? 'TRUE' : 'FALSE'; // get TRUE echo $var==FALSE ? 'TRUE' : 'FALSE'; // get FALSE ?>
and I am trying to integrate something similar as part of a single line output. My line looks like this:
echo "...text..." . $db_field['late']==0 ? ' ' : $db_field['late'] . "...more text...";
Logically what I want to do is: if 'late' = 0 then display nothing else display the content of 'late'.
Am I just trying to be too clever?
-
Graeme almost 11 yearsPerfect. Worked a treat. No idea what a 'ternary operator' is but thanks.
-
KamikazeCZ almost 11 yearsA ternary operator is what you meant by "inline if"