即使您沒有繼續阻止,您的第二個示例仍然適用於您。
$count = -1;
foreach ($lines as $item){
$count++;
switch ($item){
case "item1":
if ($count > 0){
echo '-not the first line-'; // executes as expected
}
echo "item 1 found";
break;
}
}
如果您$item == ""
這顯然是$item != "item1"
所以唯一的情況下也不會被執行。在你的示例代碼中,這相當於之前有一個繼續。我的猜測是你的$ item不是你想象的那樣。試試var_dump($item)
吧。
EDIT1:本地測試
<pre><?php
$lines = array("", "", "John Doe", "", "2011", "", "", "item1");
$count = -1;
foreach ($lines as $item){
$count++;
if ($item == ""){
echo "\t(skipping empty item)\n";
continue; // don't process empty items
}
if ($count > 0){
echo "-not the first line-\n";
}
else
echo $item." is the first line\n";
switch ($item){
case "item1":
echo "item 1 found\n";
break;
}
}
?>
將輸出
(skipping empty item)
(skipping empty item)
-not the first line-
(skipping empty item)
-not the first line-
(skipping empty item)
(skipping empty item)
-not the first line-
item 1 found
具有
$lines = array("foobar", "", "John Doe", "", "2011", "", "", "item1");
將輸出
foobar is the first line
(skipping empty item)
-not the first line-
(skipping empty item)
-not the first line-
(skipping empty item)
(skipping empty item)
-not the first line-
item 1 found
在continue-statement下面移動$count++;
,使其工作。
<pre><?php
$lines = array("", "", "John Doe", "", "2011", "", "", "item1");
$count = -1;
foreach ($lines as $item){
if ($item == ""){
echo "\t(skipping empty item)\n";
continue; // don't process empty items
}
$count++;
if ($count > 0){
echo "-not the first line-\n";
}
else
echo $item." is the first line\n";
switch ($item){
case "item1":
echo "item 1 found\n";
break;
}
}
?>
輸出
(skipping empty item)
(skipping empty item)
John Doe is the first line
(skipping empty item)
-not the first line-
(skipping empty item)
(skipping empty item)
-not the first line-
item 1 found
你能提供'$ lines'的內容是什麼? – Vitamin 2012-02-21 10:18:45
繼續在這種情況下只會執行,如果你的$ item是「」,是這樣嗎? – linuxeasy 2012-02-21 10:19:20
適合我:http://codepad.viper-7.com/cKTFYH – PeeHaa 2012-02-21 10:20:28