Athari / YaLinqo

Yet Another LINQ to Objects for PHP [Simplified BSD]
https://athari.github.io/YaLinqo
BSD 2-Clause "Simplified" License
441 stars 39 forks source link

Array of arrays - firstOrDefault by reference? #44

Closed nvirth closed 5 years ago

nvirth commented 5 years ago

I have an array of arrays.
Is it possible to get the inner arrays by reference?

Example:

$arrayOfArrays = [
    [1, 2, 3]
];
$innerArray = Enumerable::from($arrayOfArrays)
    ->where(function ($innerArray) { return true; }) // Some filter logic comes here
    ->firstOrDefault();

$innerArray[0] = 10;

echo $arrayOfArrays[0][0]; // It's 1, not 10

Thank you very much!

Athari commented 5 years ago

@nvirth Unfortunately, references in PHP is a badly broken feature. Even something as mundane as using a reference within foreach has a warning attached right there in the manual. If something like this is implemented in YaLinqo, it will cause more problems than it solves.

Furthermore, LINQ is spiritually part of functional programming which forbids modifying. (There're a few exceptions which violate the principle, but overall YaLinqo follows the paradigm.)

So, the correct approach which conforms with the functional paradigm would be to create a new array instead of mixing functional and imperative programming:

$arrayOfArrays = [
    [ 1, 2, 3 ]
];
$outputIterator = Enumerable::from($arrayOfArrays)
    ->select(function ($innerArray) {
        return $innerArray[0] == 1 ? [ 10, $innerArray[1], $innerArray[2] ] : $innerArray;
    });
echo($outputIterator->toList()[0][0]); // 10
nvirth commented 5 years ago

@Athari Thank you very much, for both the information and the solution! :)