From e708043384ab9887cfcb9aa20453f54c0d888855 Mon Sep 17 00:00:00 2001 From: Brenier Arnaud Date: Wed, 21 Feb 2024 15:17:53 +0100 Subject: [PATCH] [10.x] Arr::select not working when $keys is a string (#50169) * Arr::select not working when $keys is a string Adding a check about $keys type. If it is a string, transform it into an array. If not, it throws a foreach() error * add test --------- Co-authored-by: Taylor Otwell --- src/Illuminate/Collections/Arr.php | 2 ++ tests/Support/SupportArrTest.php | 36 ++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 291d3de39074..e75d87ae979e 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -516,6 +516,8 @@ public static function only($array, $keys) */ public static function select($array, $keys) { + $keys = static::wrap($keys); + return static::map($array, function ($item) use ($keys) { $result = []; diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index 05f6b743f3e1..119dd2a3bd65 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -1273,4 +1273,40 @@ public function testTake() 4, 5, 6, ], Arr::take($array, -3)); } + + public function testSelect() + { + $array = [ + [ + 'name' => 'Taylor', + 'role' => 'Developer', + 'age' => 1, + ], + [ + 'name' => 'Abigail', + 'role' => 'Infrastructure', + 'age' => 2, + ], + ]; + + $this->assertEquals([ + [ + 'name' => 'Taylor', + 'age' => 1, + ], + [ + 'name' => 'Abigail', + 'age' => 2, + ], + ], Arr::select($array, ['name', 'age'])); + + $this->assertEquals([ + [ + 'name' => 'Taylor', + ], + [ + 'name' => 'Abigail', + ], + ], Arr::select($array, 'name')); + } }