PHP If / Else statement not working in While loop

10,253
if ($layout = "vertical")   

should be:

if ($layout == "vertical")   

Otherwise you are assinging a value to $layout of 'vertical' opposed to comparing it's value to see if it's equal to 'vertical'. That assignment will otherwise equal to true, reason the first part runs and the ELSE does not.

One method I use to prevent accidents like this is to put the constant first such as:

if ("vertical" == $layout)   

That way if I miss the other = sign PHP will error, rather than assign the value erroneously.

Share:
10,253
Kyle
Author by

Kyle

Updated on August 02, 2022

Comments

  • Kyle
    Kyle over 1 year

    I've been working on this bit of code for about an hour and can't seem to figure out why it's not working. Does PHP allow If/Else statements within While loops? I've tried adding different echos to both If/Else statements and the latter (Else) will not show. Is this because I'm trying to use the same variable names?

    while($row = mysql_fetch_array($result))
    
    {
    
    //assign variables
    $title = $row['title'];
    $file_url = $row['file_location'];
    $category = $row['category'];
    $layout = $row['layout'];
    
    
        If ($layout = "vertical")       
        {
            //Page Layout
            $BODYLAYOUT = "vertical_body";
            $GAMECONTAIN = "vertical_gameContain";
            $GAMEWIDTH = "vertical_game";
        }
        Else
        {
            // Page Layout
            $BODYLAYOUT = "horizontal_body";
            $GAMECONTAIN = "horizontal_gameContain";
            $GAMEWIDTH = "horizontal_game";
        }