Skip to content
Advertisement

Laravel array_only with dot notation

Laravel has a helper that allows you to get only the keys you want like so:

https://laravel.com/docs/5.6/helpers#method-array-only

$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];

$slice = array_only($array, ['name', 'price']);

// ['name' => 'Desk', 'price' => 100]

However, how can I get the array_only equivalent that also allows dot notation. e.g.

$array = [
    'name' => [
        'first' => 'John',
        'last' => 'Smith',
    ],
    'levels' => [
        'maths' => 6,
        'science' => 10,
    ],
    'age' => 25,
];

$slice = array_dot_only($array, ['name.first', 'levels']);

/*
[
    'name' => [
        'first' => 'John',
    ],
    'levels' => [
        'maths' => 6,
        'science' => 10,
    ],
];
*/

Advertisement

Answer

Building off @Edwin’s answer:

function array_dot_only(array $array, $keys): array
{
    $newArray = [];
    $default = new stdClass;
    foreach ((array)$keys as $key) {
        $value = array_get($array, $key, $default);
        if ($value !== $default) {
            array_set($newArray, $key, $value);
        }
    }
    return $newArray;
}

This brings the function even closer to array_only because it will include items where the key is set but the value is null. It does so by using an object as the default and checking if the $value is that same object.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement