Skip to content

Commit 42ff290

Browse files
ecrmnntaylorotwell
andauthored
[9.x] Adds Arr::map and Arr::transform (#42398)
* Adds Arr::map and Arr::transform * remove transform Co-authored-by: Taylor Otwell <[email protected]>
1 parent 1753236 commit 42ff290

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

src/Illuminate/Collections/Arr.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,22 @@ protected static function explodePluckParameters($value, $key)
530530
return [$value, $key];
531531
}
532532

533+
/**
534+
* Run a map over each of the items in the array.
535+
*
536+
* @param array $array
537+
* @param callable $callback
538+
* @return array
539+
*/
540+
public static function map(array $array, callable $callback)
541+
{
542+
$keys = array_keys($array);
543+
544+
$items = array_map($callback, $array, $keys);
545+
546+
return array_combine($keys, $items);
547+
}
548+
533549
/**
534550
* Push an item onto the beginning of an array.
535551
*

src/Illuminate/Collections/Collection.php

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -720,11 +720,7 @@ public function pluck($value, $key = null)
720720
*/
721721
public function map(callable $callback)
722722
{
723-
$keys = array_keys($this->items);
724-
725-
$items = array_map($callback, $this->items, $keys);
726-
727-
return new static(array_combine($keys, $items));
723+
return new static(Arr::map($this->items, $callback));
728724
}
729725

730726
/**

tests/Support/SupportArrTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,6 +622,16 @@ public function testArrayPluckWithNestedArrays()
622622
$this->assertEquals([['[email protected]'], [null, null]], Arr::pluck($array, 'users.*.email'));
623623
}
624624

625+
public function testMap()
626+
{
627+
$data = ['first' => 'taylor', 'last' => 'otwell'];
628+
$mapped = Arr::map($data, function ($value, $key) {
629+
return $key.'-'.strrev($value);
630+
});
631+
$this->assertEquals(['first' => 'first-rolyat', 'last' => 'last-llewto'], $mapped);
632+
$this->assertEquals(['first' => 'taylor', 'last' => 'otwell'], $data);
633+
}
634+
625635
public function testPrepend()
626636
{
627637
$array = Arr::prepend(['one', 'two', 'three', 'four'], 'zero');

0 commit comments

Comments
 (0)