On 2 June 2017 18:21:34 BST, Levi Morrison <le...@php.net> wrote:
>On Fri, Jun 2, 2017 at 11:12 AM, Michael Morris <tendo...@gmail.com>
>wrote:
>> What about foreach by reference, which is honestly the only time I
>use
>> referencing anymore...
>>
>> foreach ($array as $key => &$value) {
>>   $value = someOp($value);
>> }
>>
>> Is this also bad?
>
>I'm not going to say "bad" but I would not personally write it that
>way. If the memory cost is too high to duplicate then ...

The times I've used foreach-by-reference have absolutely nothing to do with 
memory cost. Mostly, they're situations where explicitly writing back into the 
original array would be tediously long-winded, like this:

$some_array[$some_outer_key][$loop_key]['foo'] = some_func($loop_value['foo']);
$some_array[$some_outer_key][$loop_key]['bar'] = 
some_other_func($loop_value['bar'], true);

Granted, there are probably major refactorings that would be in some way 
better, but changing $loop_value to a reference gives the much more readable:

$loop_value['foo'] = some_func($loop_value['foo']);
$loop_value['bar'] = some_other_func($loop_value['bar'], true);

References are fiddly, but they do have their uses. Short of eliminating 
mutability, per functional programming, I think they'll always have their 
place, in some form.

Regards,

-- 
Rowan Collins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to