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 18:14:42 EDT 2013


The only reason would be poorly designed code where the return value could
change based on multiple separate conditionals.  I have seen it in some
legacy code.

On Mar 15, 2013 5:50 PM, "Anthony Ferrara" <ircmaxell at gmail.com> wrote:
>
> The first is fine. There's no reason not to do it...
>
>
> On Fri, Mar 15, 2013 at 5:30 PM, Joseph Crawford <codebowl at gmail.com>
wrote:
>>
>> 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
>>
>>
>>
>> _______________________________________________
>> New York PHP User Group Community Talk Mailing List
>> http://lists.nyphp.org/mailman/listinfo/talk
>>
>> http://www.nyphp.org/show-participation
>
>
>
> _______________________________________________
> 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/ba1a7257/attachment.html>


More information about the talk mailing list