Reputation: 4806
$array = ['key' => null];
echo data_get($array, 'key', 'default') // Result was default
$array = (object) $array;
echo data_get($array, 'key', 'default') // Result was null
Is there any specific reason it was done like this or arrays and objects?
Laravel doc ref they mentioned like this data_get function retrieves a value from a nested array or object using "dot" notation:
So it should be same behavior for both array and object
Upvotes: 0
Views: 2072
Reputation: 7992
If you check source of data_get()
, you'll notice
if (Arr::accessible($target) && Arr::exists($target, $segment)) {
$target = $target[$segment];
} elseif (is_object($target) && isset($target->{$segment})) {
$target = $target->{$segment};
} else {
return value($default);
}
and isset($target->{$segment})
which returns false
for null
and hence returns the default value for object which has null
value for the searched key.
Upvotes: 1