PHP break and continue

PHP break and continue

Last Updated on Mar 21, 2023

We have already talked about loops. Inside the loop we can use 2 words

  • break
  • continue

Let’s see what they mean and what they do.

Break

We are telling php to jump out of the loop completely and execute the rest of the code.

For example we're looking for a value inside an array. we'll check each value inside the array to see if it is what we’re looking for. When we find our value we don’t care about the rest. so we want to jump completely out of the loop and execute the rest of the code.

<?php
$names = ['Vitto','Simon','Pratham','Hassib','Thomas','Tom'];

foreach($names as $name){
    if($name == 'Pratham'){
        // found him. there is no need to continue
        break;
    }
}
// execute the rest of the code

Continue

We are telling php to skip the current iteration of the loop and execute the next one.

For example we want to echo some of the values inside an array. So if the value doesn’t have what we specified, we'll to go to the next iteration. We don’t want to completely end the loop.

$numbers = [50,250,5421,3,756,93,43];

foreach($numbers as $number){
    // skip the numbers that are divisible by 3
    if($number % 3 == 0){
        continue;
    }
    echo $number;
}
https://youtu.be/F8Z31bQ-1x8

Conclusion

Now you know about break and continue in PHP.

I recommend you to open a PHP files and write a loop. try the words continue and break and see what happens.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • continue in a loop PHP
  • break in a look PHP

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses