arrays icon indicating copy to clipboard operation
arrays copied to clipboard

Get array value by matcher

Open yus-ham opened this issue 1 year ago • 1 comments

What the problem?

https://github.com/yiisoft/arrays/blob/c3d14a3dea93edd44759de57105f02f18c135cad/src/ArrayHelper.php#L210-L212

Current implementation of getValue($array, $key) with $key as anonymous function is not match with the phrases Retrieves the value of an array element. basically it just like a value transformation, it can returns anything even value from outside array itself as of in example https://github.com/yiisoft/arrays/blob/c3d14a3dea93edd44759de57105f02f18c135cad/src/ArrayHelper.php#L184-L188

What is the expected result?

the implementation should search value of an array by matcher function

    if ($key instanceof Closure) {
        foreach ($array as $key => $value) {
            if ($key($value, $key)) {
                return $value;
            }
        }

        return $default;
    }

and then, change the signature of matcher function to be function($value, $key): bool .

Additional info

Q A
Version 1.0.?
PHP version
Operating system

yus-ham avatar Aug 30 '23 10:08 yus-ham

Looks good for me. Instead of code:

$fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) { 
    return $user->firstName . ' ' . $user->lastName; 
});

we can use:

$fullName = $user->firstName . ' ' . $user->lastName;

vjik avatar Aug 30 '23 10:08 vjik