NYCPHP Meetup

NYPHP.org

[nycphp-talk] style question: returning from a function while you're in a foreach

Joseph Crawford codebowl at gmail.com
Fri Mar 15 17:30:57 EDT 2013


There are a few things to learn from here.

First it is not only a styling thing.  In the first one you have several return
statements and in the second you only have 1 return statement.

It will depend on the code logic but I tend to return when I have the value I need rather 
than assign it to a variable and have it continue to process through the rest of the function.

If you only return after the entire function is complete but your known case was the first check in
the function you are "over" processing and will only add time to your sites load time.

Thanks,
Joseph Crawford

On Mar 15, 2013, at 5:08 PM, David Mintz wrote:

> function whatever(Array $array) {
> 
>     foreach ($array as $key => $value) {
>         if  ($something)  {
>              return true;
>         }
>     }
>     return false;
> }
> 
> Is there any reason  -- style, legibility, whatever -- not to do the above? Or should you do something like
> 
> function whatever(Array $array)  {
> 
>    $return = false;
>     foreach ($array as $key => $value) {
>         if  ($something)  {
>              $return = true;
>              break;
>         }
>     }
>     return $return;
> }
> 
> Thanks.
> 
> 
> -- 
> David Mintz
> http://davidmintz.org/
> Fight for social equality:
> http://socialequality.com/
> 
> _______________________________________________
> New York PHP User Group Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
> 
> http://www.nyphp.org/show-participation

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20130315/293ec590/attachment.html>


More information about the talk mailing list