IF/ELSE to echo image in PHP

I am trying to echo a specific image based on the results of a IF/ELSE statement, however I can't quite work out the phrasing of the IF/ELSE statement. I'm a relative newbie to PHP, so I'm sure that it's just a little error in the code somewhere, but if anyone could offer any assistance, I'd be grateful!

I'm currently at the stage below:

<?php
     $fresh = if ($reviews['reviews']['freshness']) = 'fresh' {
            echo '<img src="assets/images/fresh.png" class="rating" title="Fresh" alt="Fresh" />';
        } else {
            echo '<img src="assets/images/rotten.png" class="rating" title="Rotten" alt="Rotten" />';
        }
?>

<?php
                        foreach($reviews['reviews'] as $rv){
                            if ($tmp++ < 10);
                            echo $fresh;
                            echo '<li>' . $rv['quote'] . '</li>';
                        }
                    ?>

Thank you!


you cant assign if statement to a value.

if ($reviews['reviews']['freshness'] == 'fresh') {
            echo '<img src="assets/images/fresh.png" class="rating" title="Fresh" alt="Fresh"/>';
        } else {
            echo '<img src="assets/images/rotten.png" class="rating" title="Rotten" alt="Rotten" />';
    }

another prettier way would be:

if ($reviews['reviews']['freshness'] == 'fresh') {
   $image = "fresh";
}
else {
    $image = "rotten";
}

echo '<img src="assets/images/' . $image . '.png" class="rating" title="Rotten" alt="Rotten" />';

Yup, your code is pretty wrong, but I can see what you're trying to do.

<?php
if ($reviews['reviews']['freshness'] == 'fresh') {
    $image = '<img src="assets/images/fresh.png" class="rating" title="Fresh" alt="Fresh" />';
} else {
    $image = '<img src="assets/images/rotten.png" class="rating" title="Rotten" alt="Rotten" />';
}
?>

Your main mistake there is the incorrect positioning of brackets, and the fact that the IF statement does NOT return a value in PHP.

That said, I'm not sure why you're doing your foreach loop underneath, so I've not touched that; perhaps you could explain further what you're trying to achieve?


这可能会帮助你朝正确的方向发展:

<?php
if ($reviews['reviews']['freshness'] == 'fresh'){
    echo '<img src="assets/images/fresh.png" class="rating" title="Fresh" alt="Fresh" />';
}
else{
    echo '<img src="assets/images/rotten.png" class="rating" title="Rotten" alt="Rotten" />';
}

while($reviews['reviews']){
    for($i=0;i<10;i++{
        echo // What do you actually want to print out?
        echo '<li>'.$reviews['reviews']['quote'].'</li>';
    }
}
?>
链接地址: http://www.djcxy.com/p/12014.html

上一篇: PHP解析错误:语法错误,意外的T

下一篇: IF / ELSE在PHP中回显图像