PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 14, 2022

[FIXED] How to fix my PHP inline if using ternary operator?

 February 14, 2022     if-statement, php, syntax     No comments   

Issue

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?


Solution

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



Answered By - luiges90
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing