Skip to content

Instantly share code, notes, and snippets.

@SamuelDavis
Last active February 18, 2017 09:02
Show Gist options
  • Save SamuelDavis/f06343039881f6e4c486b44e5dee4283 to your computer and use it in GitHub Desktop.
Save SamuelDavis/f06343039881f6e4c486b44e5dee4283 to your computer and use it in GitHub Desktop.
Array helper class just like https://github.com/illuminate/support/blob/master/Arr.php except hilarious.
<?php
namespace Lib;
class Arr
{
public static function set(string $key, $value, array $container = []): array
{
list($keys, $valueKey) = static::breakKey($key);
$end = &static::seekEnd($keys, $container);
$end[$valueKey] = $value;
return $container;
}
private static function breakKey(string $key): array
{
$keys = explode('.', $key);
$valueKey = array_pop($keys);
return [$keys, $valueKey];
}
private static function &seekEnd(array $keys = [], array &$container = [])
{
$currentDepth = &$container;
foreach ($keys as $key) {
if (!is_array($currentDepth[$key] ?? null)) {
$currentDepth[$key] = [];
}
$currentDepth = &$currentDepth[$key];
}
return $currentDepth;
}
public static function append(string $key, $value, array $container = []): array
{
list($keys, $valueKey) = static::breakKey($key);
$end = &static::seekEnd($keys, $container);
if (is_array($end[$valueKey] ?? null)) {
$end[$valueKey][] = $value;
} else {
$end[$valueKey] = [$value];
}
return $container;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment