Continue or break out of a PHP loop

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 the continue keyword within a conditional. Let’s add another record to our array, this time for how to learn Nginx. We’ll update the title and content for this record. When we refresh the page, we can see the three records being outputted.

[
    'title' => 'How to learn Nginx',
    'content' => 'This is how you learn Nginx.',
],

But 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. For the condition, we can check it a specific variable contains a string of text by calling the str_contains() function. The first argument is the variable we’d like to check text against, which would be $posts[$i], meaning the current iteration of the post, and specifically the title key within this post. The second argument will be the text we’d like to search for, which is 'SQL'.

<?php for ($i = 0; $i < $numPosts; $i++) : ?>
    <?php
    if (str_contains($posts[$i]['title'], 'SQL')) :
    
    endif;
    ?>
    <h3><?= $posts[$i]['title'] ?></h3>
    <p><?= $posts[$i]['content'] ?></p>
<?php endfor ?>

This condition will return true if the title contains the text “SQL”. If we use the continue keyword within this if statement, it will skip the current iteration of the loop and precede to the next iteration. If we save & refresh the page, we will see that the MySQL post is now skipped over.

<?php for ($i = 0; $i < $numPosts; $i++) : ?>
    <?php
    if (str_contains($posts[$i]['title'], 'SQL')) :
        continue;
    endif;
    ?>
    <h3><?= $posts[$i]['title'] ?></h3>
    <p><?= $posts[$i]['content'] ?></p>
<?php endfor ?>

Similarly, we can use the break keyword to break out of a loop. So if we change continue to break & save, we’ll see that break completely exits out of the loop at the time that keyword is executed.

<?php for ($i = 0; $i < $numPosts; $i++) : ?>
    <?php
    if (str_contains($posts[$i]['title'], 'SQL')) :
        break;
    endif;
    ?>
    <h3><?= $posts[$i]['title'] ?></h3>
    <p><?= $posts[$i]['content'] ?></p>
<?php endfor ?>


Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock