get() and set()
Read and write nested array values using dot notation.
Syntax
\Illuminate\Support\Arr::get($array, 'a.b.c', $default);The Arr::get() method retrieves a value from a deeply nested array using dot notation, with an optional default if the key is missing. Arr::set() writes a value the same way, creating nested arrays as needed.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A webhook handler safely reads a deeply nested field from the incoming JSON payload using Arr::get() with a fallback default, avoiding undefined-index errors.
- A settings resolver reads theme.colors.primary from a user's stored preferences array, falling back to the application default when the key is absent.
- A test factory calls Arr::get() on the generated data array to assert that a specific nested key was written correctly by the model factory.
More examples
Read a nested value with a default
Reads nested keys safely with dot notation; returns the third argument as default when any key in the chain is missing.
use Illuminate\Support\Arr;
$payload = [
'order' => [
'customer' => ['name' => 'Alice'],
'total' => 99.99,
],
];
$name = Arr::get($payload, 'order.customer.name'); // 'Alice'
$coupon = Arr::get($payload, 'order.coupon', 'NONE'); // 'NONE'
$shipping = Arr::get($payload, 'order.shipping.fee', 0.0); // 0.0Use Arr::get on a numeric array
Dot notation works on numeric indices too, so '1.2' resolves to the element at index [1][2] of a two-dimensional array.
use Illuminate\Support\Arr;
$matrix = [
[1, 2, 3],
[4, 5, 6],
];
$val = Arr::get($matrix, '1.2'); // 6 (row 1, column 2)Validate presence before reading
Pairs Arr::has() with Arr::get() to distinguish between a missing key and one explicitly set to null or false.
use Illuminate\Support\Arr;
$settings = ['notifications' => ['email' => true]];
if (Arr::has($settings, 'notifications.sms')) {
$sms = Arr::get($settings, 'notifications.sms');
} else {
// Key absent -- use default flow
$sms = false;
}
Discussion