Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break; vs continue; vs return;

Tags:

loops

php

I downloaded a free newsletter written in php from hotscripts.com

I updated a little the code to add new functionality and I saw something I don't understand.

In the code I see:

foreach() { ...  if() ...   break;  elseif() ...   continue; } 

I also saw:

function() { // ... for($nl = 0; ...  if() ...   return true; } 

I read that break; will stop the loop, continue will skip the loop to the next iteration and return will exit the function.

What I don't understand is why coding that style? Why not use something like:

function() { // ...  for($nl = 0; ...   if() ...    $returnValue = true;   else {    $returnValue = false;   }  }  return $returnValue; } 

or same idea in the for loops?

like image 933
Joanna Lancaster Avatar asked Dec 23 '11 14:12

Joanna Lancaster


People also ask

What is difference between break and return?

break is used to exit (escape) the for -loop, while -loop, switch -statement that you are currently executing. return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).

What is return break continue in Java?

The break statement is used to terminate the loop immediately. The continue statement is used to skip the current iteration of the loop. break keyword is used to indicate break statements in java programming. continue keyword is used to indicate continue statement in java programming.

Does return act as break?

Answer 533416ba631fe960060022a4 No. return jumps back directly to the function call returning the value after it and everything (in a function) that is after an executed return statement is ignored. So return itself can act as a break statement for functions and no further break is required.


1 Answers

Using keywords such as break and continue can make the code far easier to read than what you propose.

Especially if you are nesting if/else-statements more than one level.

Compare the snippets further down in this post, which one is easier to read? Both of them output the same exact thing, and $A is array (1,2,4,4,3,4).

A return in a loop (inside a function) can save precious CPU cycles, if you know you don't need to loop any further, why do it?


I'm too cool to use break/continue..

$not_even_found = false;  foreach ($A as $v) {   if ($v != 1) {     if ($not_even_found) {     } else if ($v % 2 != 0) {       $not_even_found = true;     } else {       echo "$v\n";     }   } } 

I want to have readable code..

foreach ($A as $v) {   if ($v == 1)     continue;    if ($v % 2 != 0)     break;    echo "$v\n"; } 
like image 106
Filip Roséen - refp Avatar answered Oct 19 '22 05:10

Filip Roséen - refp