Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use break and continue in PHP?

Tags:

php

Is it a good practice to use break and continue as sentinel for loops in PHP?

e.g.

if (!empty($var))
    break;
like image 468
user267637 Avatar asked Feb 28 '23 12:02

user267637


1 Answers

do {
 if (condition1)
   break;
 some code;
 some code;
 if (condition2)
   break;
 some code;
 some code;
 if (condition3)
   break;
 some code;
 some code;
} while (false);

vs.

if (!condition1) {
   some code; 
   some code;
   if (!condition2) {
      some code;
      some code;
      if (!condition3) {
         some code;
         some code;
      }
}

Some find the first version an abhomination and difficult to read and love the second version. Some find the first version cleaner and easier to read. As the number of conditions multiply, I tend to find the first version easier to follow, as the second one tends to get more and more difficult to follow the level of nesting. Also if the if (condition) break; gets into something only slightly more complex like if (condition) {some code; break}, the do {if .. break; if .. break..;} while(false) pattern gets even more clear compared with equivalend nested ifs.

like image 99
Remus Rusanu Avatar answered Mar 07 '23 22:03

Remus Rusanu