Question

This seems like a very stupid question, but without making any changes to the server.. the continue function in PHP seems to have started working incorrectly.

For example:

function contTest(){
    $testers = array(1, 3, 4, 5);
    foreach($testers as $test){
        echo "Got here<br>";
        continue;
        echo $test."<br>";
    }
}

Outputs:

Got here
Got here
Got here
Got here

Whereas:

function contTest(){
    $testers = array(1, 3, 4, 5);
    foreach($testers as $test){
        echo "Got here<br>";
        echo $test."<br>";
    }
}

Ouputs:

Got here
1
Got here
3
Got here
4
Got here
5

I have used this function before and it did not seem to have this effect. Any ideas? Like I said, nothing on the server has changed so the PHP version is the same.

Was it helpful?

Solution

I don’t know what effect you want, but this example is working correctly. continue needs to break current iteration and go to the next without executing code below this operator. And this function works in this case all the time since PHP 4.

OTHER TIPS

I think you need to understand how continue works. i wanted to add some, so that if some body else confronts the same, may have this as reference.

You need to use the key word continue When you want ignore the next iteration of a loop. continue is always used with if condition

According to example here .

function contTest(){
    $testers = array(1, 3, 4, 5);
    foreach($testers as $test){
        echo "Got here<br>";
        **continue;**
        echo $test."<br>";
    }
}

This works as expected and perfect and here is why. You are looping through the array $testers which has four elements inside and after getting every element , you are telling php to ignore the elements by using continue and that is the reason why it will not output the elements of the array $testers.

Let me try to rewrite your Example here.

function contTest(){
    $testers = array(1, 3, 4, 5);
    foreach($testers as $test){
        echo "Got here<br>";
        if ($test == 1):
        continue;
        endif;
        echo $test."<br>";
    }
}

echo contTest(); 

I have just used continue if element is equal to 1, meaning that element will be skipped (ignored). The output is :

Got here
Got here
3
Got here
4
Got here
5

As you can see 1 is ignored.

The continue basically says ignore the rest of the code after continue and start with the next step of the foreach loop. So the result you are getting is perfectly okay (see http://www.php.net/manual/de/control-structures.continue.php). There must be some other effect that changed your output.

This is what continue does exactly:

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration. -- http://www.php.net/manual/en/control-structures.continue.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top