[英]Using an if statement to echo text inside a while loop
我現在正在處理一項任務。 循環應該從變量 1 開始計數到 10。當循環到達數字 3 和 7 時,我需要在數字旁邊回顯一條語句。
這是我的代碼:
<?php
$x = 1;
while($x <= 10) {
echo "The number is " . $x . "<br />";
$x = $x + 1; // increment by 1 … same as $x++;
}
if ($x = $x + 2) {
echo "<font color='green'>Third time is a charm</font>";
// echo "<p>Third time is a charm</p>";
} else if ($x = $x + 6) {
echo "<br>";
echo "<font color='blue'>You got 7! JACKPOT!</font>";
}
?>
我想知道如何在語句旁邊顯示 echo 輸出。 我不知道為什么我的 if 語句現在不起作用?
你的 if 語句在你的 while 循環之外,當它達到你的條件時, $x 只是'10'(err 11)。
如果您不必使用“while”循環,則可以在 for 中實現這種清潔。
for ($i=0; $i<=10; $i++) {
//conditionals (I would elaborate, but learning by trial and error is great, don't want to rob you of that)
}
如果由於分配原因需要使用一段時間,只需將“if”之前的大括號移動到腳本末尾..即,
while {
if() {
} elseif() {
}
}
祝你好運!
<?php
$x = 1;
while($x <= 10) {
echo "The number is " . $x . "<br />";
if ($x == 3) {
echo "<font color='green'>Third time is a charm</font>";
// echo "<p>Third time is a charm</p>";
} else if ($x == 7) {
echo "<br>";
echo "<font color='blue'>You got 7! JACKPOT!</font>";
}
$x = $x + 1; // increment by 1 … same as $x++;
}
?>
嘗試這個
<?php
// $i = 1 : start the counter at 1
// $i <= 10 : execute until 10 is reached
// $i++ : increment counter by one
for($i = 1; $i <= 10; $i++) {
echo "The number is " . $i;
if($i == 3) {
echo "<font color='green'> Third time is a charm</font>";
} elseif($i == 7) {
echo "<font color='blue'> You got 7! JACKPOT!</font>";
}
echo "<br />";
}
?>
玩轉 for 循環。 它們經常派上用場。
你的if
語句在你的while
循環之外。 {}
表示基於while
語句()
中的條件運行的代碼塊,因此您需要將它們放在{
和結尾}
。 嘗試這樣的事情:
<?php
$x=0;
// You can add the increment modifier inside the
// condition too, which will save you a line of code. (Just a shortcut)
while (++$x <= 10) {
echo "The number is " . $x . "<br />";
if ($x == 3) {
echo "<font color='green'>Third time is a charm</font>";
// echo "<p>Third time is a charm</p>";
} else if ($x == 7) {
echo "<br>";
echo "<font color='blue'>You got 7! JACKPOT!</font>";
}
}
?>
或在 switch 中:(如果你想處理的不僅僅是 3 和 7,switch 可能是最干凈的方式。)
<?php
$x=0;
// You can add the increment modifier inside the
// condition too, which will save you a line of code. (Just a shortcut)
while (++$x <= 10) {
echo "The number is " . $x . "<br />";
switch ($x) {
case 3:
echo "<font color='green'>Third time is a charm</font>";
// echo "<p>Third time is a charm</p>";
break;
case 7:
echo "<br>";
echo "<font color='blue'>You got 7! JACKPOT!</font>";
break;
default:
// The default logic goes here.
}
}
?>
確保使用兩個等號來比較值,因為一個等號只會為左側的變量賦值,右側的語句。
$x = 1; // Assignment.
相比
$x == 1; // Comparison.
PS $x++
與$x = $x + 1
,只是一種簡寫方式。 如果++
在變量之前(例如++$x
),則該值將在評估語句之前遞增。 如果它在之后(例如$x++
),該語句將首先被評估(例如$x <= 10
),然后該值將在之后遞增。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.