Search code examples
phpmybb

Calling a PHP variable in a IF statement?


I am working with MyBB and I am a beginner PHP user. I am trying to display some CSS code depending on if a variable is 0 or higher. My PHP code is as follows.

<?php

if({$GLOBALS['threadfields']['trdfprice']} > 0){

   echo '<style type="text/css">
    p.price {
        display:inline; 
        padding:3px; 
        border-radius:7px; 
        background:#66CD00;}
    </style>';

} else {
   echo '<style type="text/css">
    p.price {
        display: none;}
    </style>';
}
?>

I am working with something called xThreads so it gives me custom fields for certain forums. I am able to call that variable just by using

{$GLOBALS['threadfields']['trdfprice']}

If I were to echo it I could by doing:

<?php
echo "{$GLOBALS['threadfields']['trdfprice']}";
?>

That above works, however when I try to run it in the IF statement it gives me a error:

Parse error: syntax error, unexpected '{' 

On this line

if({$GLOBALS['threadfields']['trdfprice']} > 0){

I was able to figure it out.

<?php

if( $GLOBALS['threadfields']['trdfprice'] > 0){
    echo "<p style=\"display:inline; border-radius:7px; background:#66CD00; padding:3px;\">{$GLOBALS['threadfields']['trdfprice']}</p>";

}
?>

I put that inline where it should display and it works.


Solution

  • Change this line:

    if({$GLOBALS['threadfields']['trdfprice']} > 0){
    

    to this:

    if($GLOBALS['threadfields']['trdfprice'] > 0){
    

    Additional braces should not be present in if statements hence the error you are getting:

    Parse error: syntax error, unexpected '{'