即使您没有继续阻止,您的第二个示例仍然适用于您。
$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