Skip to content

Commit 8a819db

Browse files
onairmarcEncoreBot
andauthored
Add Arr::renameKey() and Arr::addAfter() (#68)
Co-authored-by: EncoreBot <ghbot@encoredigitalgroup.com>
1 parent 9936f97 commit 8a819db

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

.git-blame-ignore-revs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ d676999a6145177a6f61007806f5b95f1df868bd
3636
53d9e752575f07527143ccee692673b8c6793141
3737
8334d091011e09e060e476cb29a17239627e9a39
3838
edb78e6307a371aff090127ce28aae9369605af8
39+
25c8e2da0ba2d49965926137dd8c26aede06ff32

src/Objects/Support/Types/Arr.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,37 @@ public static function empty(): array
1010
{
1111
return [];
1212
}
13+
14+
public static function renameKey(array $array, string $oldKey, string $newKey): array
15+
{
16+
if (!array_key_exists($oldKey, $array)) {
17+
return $array;
18+
}
19+
20+
$keys = array_keys($array);
21+
$index = array_search($oldKey, $keys, true);
22+
23+
$keys[$index] = $newKey;
24+
$values = array_values($array);
25+
26+
return array_combine($keys, $values);
27+
}
28+
29+
public static function addAfter(array $array, string $afterKey, string $newKey, mixed $newValue): array
30+
{
31+
if (!array_key_exists($afterKey, $array)) {
32+
return $array;
33+
}
34+
35+
$newArray = [];
36+
foreach ($array as $key => $value) {
37+
$newArray[$key] = $value;
38+
39+
if ($key === $afterKey) {
40+
$newArray[$newKey] = $newValue;
41+
}
42+
}
43+
44+
return $newArray;
45+
}
1346
}

0 commit comments

Comments
 (0)