Php操作员`break`不会停止

时间:2014-10-16 19:26:46

标签: php

有一个奇怪的问题,break不会在循环中断开并继续旋转。逻辑上它应该打破循环并设置一些输出

    while ($c++ != 5)
    {
        // here is curl request, doesn't relevant so I have removed it 

        preg_match("!<.*?>(\S*)[^<>]*?{$to}<!", $resp, $result) ;
        //
        echo 'cnt = ' .count($result).'<br>';
        if(!count($result))
        {
            $amount = 0;
            echo 'sleep called';
            sleep(4);
            exit;
            continue;
        }
        else
        {
            $amount = trim(@$result[1]);
            $amount = round($amount + $amount * $exchange_ratio, $precision);
            echo 'break happen<br>';
            break;
        }
    }

所以输出是

cnt = 2
break happen
cnt = 0
sleep called

所以它跳过break并继续旋转。怎么样?

EDIT 在我的本地主机上运行正常,所以问题可能与php版本有关吗?

1 个答案:

答案 0 :(得分:1)

您必须多次运行此代码:是否有第二次调用此脚本,或者第二次循环此部分?看看我的测试代码:它在休息后明显中断:

  

$ cat tmp.php

<?php 

$c = 0;
 while ($c++ != 5)
 {
     if(false) //just emulating you
     {
         $amount = 0;
         echo 'sleep called';
         sleep(4);
         exit;
         continue; //this will never be called by the way
     }
     else
     {
         echo 'break happen<br>';
         break; //this indeed breaks out of the while
     }
 }

$ php tmp.php
break happen<br>$

($是下一个提示,与我没有换行的同一行:))