Search code examples
phpmysqlzerocomparison-operators

Comparison operator problem, when template variable is zero


On a content.php page I have the following:

$html_videos = '';
if (!empty($videos)) {
    foreach ($videos as $key => $video) {
        $video = PT_GetVideoByID($video, 0, 0, 0);
        $html_videos .= PT_LoadPage('videos/list', array(
            'SELL_VIDEO' => $video->sell_video, 
            'RENT_PRICE' => $video->rent_price 
        ));
    }
}

On the list.html page that it loads, I have

            <?php $affitta = '{{RENT_PRICE}}'; echo $affitta; if (!empty($affitta) && $affitta !== 0) { ?><span class="bold">|</span> {{LANG rent}} <span style='color:#a84849;font-weight:500;'>$ {{RENT_PRICE}}</span><?php } else { echo "FREE"; } ?>

{{LANG rent}} equals to "Rent"

Var $affitta echoes fine all the times; however, be it 0 or 5 it always returns the span, hence "Rent $affitta value" while instead when $affitta equals zero I want it to return "FREE".

I have tried to use && $affitta !== '0' with quotes but same behavior. If it may help, column in database is integer and default value is 0. So, what I'm trying to do is to show FREE if RENT_PRICE ($affitta) is zero or rent price if different than zero, but no matter what I try I can never get it to recognize $affitta as zero, although the echo shows that it is zero.

I have extensively searched for an answer and tried various other suggested solution, but with no success.

I hope I have been clear and if not, please, let me know and allow me to clarify. What is it that I'm doing wrong?


Solution

  • Your life would be easier if, with the last line of code there (in list.html), you didn't jump in and out of PHP over and over. This line:

    <?php $affitta = '{{RENT_PRICE}}'; echo $affitta; if (!empty($affitta) && $affitta !== 0) { ?><span class="bold">|</span> {{LANG rent}} <span style='color:#a84849;font-weight:500;'>$ {{RENT_PRICE}}</span><?php } else { echo "FREE"; } ?>
    

    Is simply this:

    <?php 
    $affitta = '{{RENT_PRICE}}'; 
    echo $affitta; 
    if (!empty($affitta) && $affitta !== 0) { 
        echo '<span class="bold">|</span> {{LANG rent}} <span style="color:#a84849;font-weight:500;">$ {{RENT_PRICE}}</span>';
    } else { 
        echo "FREE"; 
    } 
    

    Then, with something more readable, it's very easy to see where your problem lies. You define the value of $affitta as '{{RENT_PRICE}}', which obviously doesn't equal 0 or whatever the price may be. Your templating system will substitute {{RENT_PRICE}} with the actual value, but here it's not a number. You are in fact evaluating: if ('{{RENT_PRICE}}' !== 0) {...

    You need to instead compare with the value in $video->rent_price earlier up your code. How you access that value depends entirely on what's happening inside your PT_LoadPage function.