Skip to content
This repository was archived by the owner on Feb 6, 2023. It is now read-only.

Commit 9fc81ab

Browse files
Fix array helpers
Without using any other packages.
1 parent 2a7a25c commit 9fc81ab

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/Functions/generic.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use Carbon\Carbon;
44
use SebastiaanLuca\PhpHelpers\Classes\MethodHelper;
5+
use SebastiaanLuca\PhpHelpers\InternalHelpers;
56

67
if (! function_exists('rand_bool')) {
78
/**
@@ -64,8 +65,7 @@ function array_expand(array $array) : array
6465
$expanded = [];
6566

6667
foreach ($array as $key => $value) {
67-
// FIXME
68-
array_set($expanded, $key, $value);
68+
InternalHelpers::arraySet($expanded, $key, $value);
6969
}
7070

7171
return $expanded;
@@ -83,8 +83,9 @@ function array_expand(array $array) : array
8383
*/
8484
function array_without(array $array, $values) : array
8585
{
86-
// FIXME
87-
return array_values(array_diff($array, array_wrap($values)));
86+
$values = ! is_array($values) ? [$values] : $values;
87+
88+
return array_values(array_diff($array, $values));
8889
}
8990
}
9091

src/InternalHelpers.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SebastiaanLuca\PhpHelpers;
6+
7+
class InternalHelpers
8+
{
9+
/**
10+
* Set an array item to a given value using "dot" notation.
11+
*
12+
* If no key is given to the method, the entire array will be replaced.
13+
*
14+
* @param array $array
15+
* @param string $key
16+
* @param mixed $value
17+
*
18+
* @return array
19+
*/
20+
public static function arraySet(array &$array, string $key, $value) : array
21+
{
22+
$keys = explode('.', $key);
23+
24+
while (count($keys) > 1) {
25+
$key = array_shift($keys);
26+
27+
// If the key doesn't exist at this depth, we will just create an empty array
28+
// to hold the next value, allowing us to create the arrays to hold final
29+
// values at the correct depth. Then we'll keep digging into the array.
30+
if (! isset($array[$key]) || ! is_array($array[$key])) {
31+
$array[$key] = [];
32+
}
33+
34+
$array = &$array[$key];
35+
}
36+
37+
$array[array_shift($keys)] = $value;
38+
39+
return $array;
40+
}
41+
}

0 commit comments

Comments
 (0)