Skip to content

Commit 41e7719

Browse files
[12.x] Add Arr::push() (#56632)
* Add Arr::push method with dot notation support Introduces Arr::push to append items to arrays using dot notation. Includes tests for pushing values to nested arrays, handling null keys, and exception cases for invalid types. * Allow Arr::push to accept multiple values This better matches array_push's signature * Update Arr.php --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent f64a924 commit 41e7719

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/Illuminate/Collections/Arr.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,6 +961,23 @@ public static function set(&$array, $key, $value)
961961
return $array;
962962
}
963963

964+
/**
965+
* Push an item into an array using "dot" notation.
966+
*
967+
* @param \ArrayAccess|array $array
968+
* @param string|int|null $key
969+
* @param mixed $values
970+
* @return array
971+
*/
972+
public static function push(ArrayAccess|array &$array, string|int|null $key, mixed ...$values): array
973+
{
974+
$target = static::array($array, $key, []);
975+
976+
array_push($target, ...$values);
977+
978+
return static::set($array, $key, $target);
979+
}
980+
964981
/**
965982
* Shuffle the given array and return the result.
966983
*

tests/Support/SupportArrTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,31 @@ public function testAdd()
7070
$this->assertEquals(['category' => ['type' => 'Table']], Arr::add(['category' => ['type' => 'Table']], 'category.type', 'Chair'));
7171
}
7272

73+
public function testPush()
74+
{
75+
$array = [];
76+
77+
Arr::push($array, 'office.furniture', 'Desk');
78+
$this->assertEquals(['Desk'], $array['office']['furniture']);
79+
80+
Arr::push($array, 'office.furniture', 'Chair', 'Lamp');
81+
$this->assertEquals(['Desk', 'Chair', 'Lamp'], $array['office']['furniture']);
82+
83+
$array = [];
84+
85+
Arr::push($array, null, 'Chris', 'Nuno');
86+
$this->assertEquals(['Chris', 'Nuno'], $array);
87+
88+
Arr::push($array, null, 'Taylor');
89+
$this->assertEquals(['Chris', 'Nuno', 'Taylor'], $array);
90+
91+
$this->expectException(InvalidArgumentException::class);
92+
$this->expectExceptionMessage('Array value for key [foo.bar] must be an array, boolean found.');
93+
94+
$array = ['foo' => ['bar' => false]];
95+
Arr::push($array, 'foo.bar', 'baz');
96+
}
97+
7398
public function testCollapse()
7499
{
75100
// Normal case: a two-dimensional array with different elements

0 commit comments

Comments
 (0)