PHP-If和else语句

PHP-If和else语句,php,if-statement,Php,If Statement,我有这个代码,其中有一个bug,但我看不出哪里出了问题。有人能帮忙吗?问题是,我试图显示一个特定的图像,以与文本文件的内容相一致。我想我已对该部分进行了排序,但在显示图像时,始终存在一个bug(例如,即使if语句表示otherwize,它也始终为绿色。以下是代码: <?php if (empty($_GET['unit'])) { $output="Please Enter A Unit Number"; echo $

我有这个代码,其中有一个bug,但我看不出哪里出了问题。有人能帮忙吗?问题是,我试图显示一个特定的图像,以与文本文件的内容相一致。我想我已对该部分进行了排序,但在显示图像时,始终存在一个bug(例如,即使if语句表示otherwize,它也始终为绿色。以下是代码:

<?php
            if (empty($_GET['unit'])) {
            $output="Please Enter A Unit Number";
            echo $output;
            }
            else {
                $filepathhalf = "/data/";
                $file = "false";
                $date = date("Ymd");
                $unitnum = $_GET['unit'];
                $ext = ".txt";
                $filepath = $filepathhalf.$unitnum.$date.$ext;
                echo $filepath;
                echo $file;
                if(file_exists($filepath))
                {
                    $fh = fopen($filepath, 'r');
                    $file = fread($fh, 5);
                    fclose($fh);
                }
                echo $file; //This echo comes back as false as set but the green.png image still displays.
                if ($file = "true ")
                {
                    echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
                }                   
                else 
                {
                    echo "<img src=\"images/red.png\" width=\"15\" height=\"15\" />";
                }
                echo $_GET['unit']; 
            }
            ?>  

比较两个实例和将一个实例分配给另一个实例之间存在差异

请参阅代码段中的以下几行,并查看是否可以根据上述线索发现错误:

if ($file = "true ")
{
  echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}                   
else 
{
  echo "<img src=\"images/red.png\" width=\"15\" height=\"15\" />";
}
if($file=“true”)
{
回声“;
}                   
其他的
{
回声“;
}
否则将鼠标悬停在下面的扰流板上!

如果你想得到关于这个问题的解释,也可以这样做

$file=“true”
将始终计算为true,首先是它 将字符串“true”分配给
$file
,然后分配 将对$file进行评估。

您很可能正在查找
if($file==true)
,它将
$file
的值与
的值进行比较


您可以使用一个
=
,用于分配变量,而不是比较变量。当检查两个值是否相等时,请使用
=
if($file==true)
  if ($file == true)
  {
          echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
  }   
{ 回声“; }

希望对您有所帮助,检查条件应该是
=

 if ($file != "false")
 {
   echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
 } 
if($file!=“false”)
{
回声“;
} 

您不仅使用了一个“=”,而且还将其与“true”进行比较(使用串联空格!)。我将代码更改为:

if ($file === true)
{
   echo "<img src=\"images/green.png\" width=\"15\" height=\"15\" />";
}
if($file==true)
{
回声“;
}

谢谢大家指出:)我会接受第一个答案,因为我只能接受一个。尽管你不应该在一个文件中混入顾虑,但你可能会发现,在PHP中输入和输出HTML输出是有利的:
如果($file):?>“/>@Nicholas没问题,伙计,很高兴为你服务!