10

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?

2 Answers 2

30

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...";

PHP Operator precedence

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Worked a treat. No idea what a 'ternary operator' is but thanks.
A ternary operator is what you meant by "inline if"
3
echo "...text..." . ( $db_field['late']==0 ? ' ' : $db_field['late'] )  . "...more text...";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.