Skip to content

Commit 7b2050b

Browse files
committed
Arrays::insertAfter() & insertBefore() fixed when $key is null
1 parent 42db826 commit 7b2050b

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

src/Utils/Arrays.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ public static function last(array $array)
136136
*/
137137
public static function insertBefore(array &$array, $key, array $inserted): void
138138
{
139-
$offset = (int) self::getKeyOffset($array, $key);
139+
$offset = $key === null ? 0 : (int) self::getKeyOffset($array, $key);
140140
$array = array_slice($array, 0, $offset, true)
141141
+ $inserted
142142
+ array_slice($array, $offset, count($array), true);
@@ -150,11 +150,12 @@ public static function insertBefore(array &$array, $key, array $inserted): void
150150
*/
151151
public static function insertAfter(array &$array, $key, array $inserted): void
152152
{
153-
$offset = self::getKeyOffset($array, $key);
154-
$offset = $offset === null ? count($array) : $offset + 1;
155-
$array = array_slice($array, 0, $offset, true)
153+
if ($key === null || ($offset = self::getKeyOffset($array, $key)) === null) {
154+
$offset = count($array) - 1;
155+
}
156+
$array = array_slice($array, 0, $offset + 1, true)
156157
+ $inserted
157-
+ array_slice($array, $offset, count($array), true);
158+
+ array_slice($array, $offset + 1, count($array), true);
158159
}
159160

160161

tests/Utils/Arrays.insertBefore().phpt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ test('First item', function () use ($arr) {
3737
Arrays::insertAfter($dolly, null, ['new' => 'value']);
3838
Assert::same([
3939
'' => 'first',
40-
'new' => 'value',
4140
0 => 'second',
4241
1 => 'third',
4342
7 => 'fourth',
43+
'new' => 'value',
4444
], $dolly);
4545
});
4646

0 commit comments

Comments
 (0)