簡體   English   中英

PHP-If和else語句

[英]PHP - If and else statements

我有這段代碼,上面有一個錯誤,但是我看不到哪里出錯了。 有人可以幫忙嗎? 問題是我試圖顯示某個圖像以與文本文件的內容相對應。 我認為我已經對那部分進行了排序,但是當涉及到顯示圖像時,總是有一個bug(即使if語句說出otherwize,EG也總是綠色的,這是代碼:

<?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\" />";
}

否則,將鼠標懸停在下面的擾流板上!

如果您想對此問題進行解釋,請執行相同的操作...

$file = "true "將始終評估為true,首先將字符串“ true” 分配$file ,然后將評估$file值。

您最有可能在尋找if($file == true) ,它將 $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\" />";
 } 

不僅您使用的是單個“ =”,而且還將其與“ true”(帶連接的空格!)進行比較。 我將代碼更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM