98 words, 1 min read
In Laravel, Arr::get()
is a convenient way to safely retrieve a value from an array, with the option to specify a default value.
However, the default is only used when the key does not exist—not when the value is null
.
$arr = ["data" => null];
// ❌ Not what you might expect
Arr::get($arr, "data", []); // returns null
// ✅ Correct way to ensure a default for null values
Arr::get($arr, "data") ?? []; // returns []
So if you need a fallback even when the value is null
, remember to use the null coalescing operator (??
) after Arr::get()
.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.