Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Inline IF

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?

like image 958
Graeme Avatar asked Jun 10 '13 02:06

Graeme


2 Answers

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

like image 59
luiges90 Avatar answered Oct 16 '22 15:10

luiges90


echo "...text..." . ( $db_field['late']==0 ? ' ' : $db_field['late'] )  . "...more text...";
like image 20
蒋艾伦 Avatar answered Oct 16 '22 16:10

蒋艾伦