PHP If/Else 语句在 While 循环中不起作用 [英] PHP If / Else statement not working in While loop

查看:46
本文介绍了PHP If/Else 语句在 While 循环中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经研究了这段代码大约一个小时,但似乎无法弄清楚为什么它不起作用.PHP 是否允许在 While 循环中使用 If/Else 语句?我尝试向 If/Else 语句添加不同的回声,而后者 (Else) 不会显示.这是因为我试图使用相同的变量名称吗?

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";
    }

推荐答案

if ($layout = "vertical")   

应该是:

if ($layout == "vertical")   

否则,您正在为垂直"的 $layout 分配一个值,而不是比较它的值以查看它是否等于垂直".否则该赋值将等于 true,原因是第一部分运行而 ELSE 不运行.

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)   

那样的话,如果我错过另一个 = 符号 PHP 会出错,而不是错误地分配值.

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

这篇关于PHP If/Else 语句在 While 循环中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆