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?
Source: Tips4all
Using keywords such as break and continue can make the code far easier to read than what you propose.
ReplyDeleteEspecially 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";
}
You code using that style so that you save unnecessary loops when the first time a condition is met then you already now that something is true and you don't need to investigate further.
ReplyDeleteIn fact if you return you stop the loop. A stupid example
function in_array($needle, $haystack){
for($i = 0; $i < count($haystack); i++){
if($needle === $haystack[$i]{
return $i;
}
}
return -1;
}
in this case when the condition is met you return something (true, or in this case the value of the counter) because you don't need to iterato over the whole array
Some of the "why" comes down to personal preference. Some of it comes down to whether other things need to be done in the same function before it returns. If there's nothing else that needs to be done, and the function is simply supposed to return a true or false answer, then directly using return true; is the most expedient mechanism. If you still need to do some other stuff even after deciding whether to return true or not (close a file handle for example), then assigning the response to a variable and then returning that at the end may be necessary.
ReplyDelete