user1145101
user1145101

Reputation: 27

PHP While loop not breaking, but works in debugger?

Have a simple script that loops through. Works fine in debugger mode when i step through code. But when its ran on without debugger it never ends / breaks.

Should run for as long as the time i set then break out of the loop. As i said this works perfectly fine in debugger, but when its ran without it, it just forever loops regardless of the time

Any suggestions why?

$time_start = microtime(true);
$n = 0;
while ( 1 ){
    $n++ ;
    echo $n;
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    if($time > 1.5){
        break;
    }
}

I want to use While, as the program will be used to listen to a socket. but need to ensure the while ends if a time is met

Upvotes: 0

Views: 65

Answers (1)

Markus Zeller
Markus Zeller

Reputation: 9145

It works, but PHP is very fast. So you have to be more patient, until the time is passed. Put your threshold down.

Maybe you should consider using hrtime instead.

When you are using the debugger, time is still running, so the delay until your next step is reached, is quickly over and meets the break condition.

$time_start = microtime(true);
$n = 0;
while ( 1 ){
    $n++ ;
    echo $n;
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo " :: $time\n";
    if($time > 1.5){
        break;
    }
}

See the last results after slightly modifying your output.

1354524 :: 1.4999921321869
1354525 :: 1.4999930858612
1354526 :: 1.4999940395355
1354527 :: 1.4999949932098
1354528 :: 1.4999949932098
1354529 :: 1.4999961853027
1354530 :: 1.4999971389771
1354531 :: 1.4999980926514
1354532 :: 1.4999990463257
1354533 :: 1.4999990463257
1354534 :: 1.5
1354535 :: 1.5000011920929

Upvotes: 1

Related Questions