meowwwwww meowwwwww - 7 months ago 11
PHP Question

if statements in while loop?

Hi I am just wondering how do if statements work in while (loop)?
I want the page to display number through 1 to 10 and show special comment for number 1 and 2.
Thanks so much!

<?php
$x=1;
while($x <= 10) {
echo "". $x . "<br />";
$x = $x + 1; }

if ($x = 1 ) {
echo "".$comment."";
$comment = "this is one!";}
elseif ($x = 2) {
echo "".$comment."";
$comment = "this is two!";}

?>




Ben Ben
Answer

First - you need to make sure that your IF conditions are inside your while loop. Also, you should read up on the difference between a single equals sign and a double equals (in this case, you want the double equals == as you're testing for equality).

My take on your code would be something like the following:

<?php
$x = 1;
while( $x <= 10) {
    $comment = "";

    if ($x == 1 ) {
        $comment = "This is one!";
    }

    if ($x == 2) {
        $comment = "This is two!";
    }


    echo $x . " " . $comment . "<br />\n";
    $x = $x + 1; 
}

This yields:

1 This is one!<br />
2 This is two!<br />
3 <br />
4 <br />
5 <br />
6 <br />
7 <br />
8 <br />
9 <br />
10 <br />
Comments