[英]Foreach while loop php issue
我試圖只在每行的新行上顯示此數組中不為空的名稱。 當前,使用它只能顯示“ $ playerName1”的名稱10次。 我試圖弄清楚為什么它實際上沒有遍歷所有10個玩家名。 看來只在檢查$ playerName1。
$z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $playerName10);
$zCounter = 1;
foreach ($z as $allNames) {
while ($allNames != "" && $zCounter < 11) {
echo $allNames . "<br>";
$zCounter++;
}
}
您的問題是您只需要第一個玩家名稱就可以進入內部while
循環。 外層的foreach
循環應該足夠多:
foreach ($z as $playerName) {
if ("" !== $playerName) {
echo $playerName . "<br />";
}
}
除非要輸出每個name
10次,否則請刪除while
循環。 您仍然可以使用!=''
或empty()
來確保名稱不為空
<?php
$z = array($playerName1, $playerName2, $playerName3, $playerName4, $playerName5, $playerName6, $playerName7, $playerName8, $playerName9, $playerName10);
foreach($z as $name){
if(!empty($name)){
echo $name.'<br>';
}
}
您需要在每個while循環后重置$ zCounter
foreach ($z as $allNames) {
while ($allNames != "" && $zCounter < 11) {
echo $allNames . "<br>";
$zCounter++;
}
$zCounter = 0;
}
否則,在第一個while循環結束后,$ zCounter將始終為11
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.