1. 29
    Continue or break out of a PHP loop
    2m 18s

Continue or break out of a PHP loop

Mark Shust
InstructorMark Shust

Share this video with your friends

Send Tweet
Published 7 months ago
Updated 6 months ago

Sometimes you need to escape out of a PHP loop. You can easily do this by using either the continue or break keywords.

Mark Shust: [0:00] It's possible to either skip over the current iteration of a loop or break out of it. To skip over the current iteration, you can use a continue keyword within a conditional. Let's add another record onto this array, this time for "How to Learn NGINX." When we save and refresh the page, we will see that there are now three posts, and the last one being How to Learn NGINX. [0:27] Let's say we wanted to skip over blog post titles that contain the text "SQL." We can do this by writing an if statement within the foreach loop and then continuing with the loop. Let's create a new PHP tag, and we will write an if statement. For the condition, we can check if a specific variable contains a string of text by calling the str_contains() function. This function accepts two arguments.

[0:58] The first argument is the variable we'd like to check text against. This will be the current iteration of the loop, which is POSTS [$i] , and then we are checking against the title key. The second argument is the text we'd like to search for, which would be "SQL." Finally, we will close up this if statement with an endif.

[1:27] This condition will return true if the title contains the text "SQL." If this matches, let's call the continue keyword. This will skip over the current iteration of the loop, not outputting the lines that follow it. If we save and refresh the page, we will see that that "How to Learn MySQL" post is completely skipped over, but the NGINX post is still outputted.

[1:54] Similarly, we can use the break keyword to completely break out of a loop. If we change continue to break and refresh the page, you will see that break completely exits out of the loop and only outputs the first iteration. This is useful if you wanted to prevent the loop from further executing based on a certain condition.