I'm working on arrays or objects with many optional fields. I'm trying to check field values without getting a PHP error, which lead me to :
$name = isset($revision['data']['name']) ? $revision['data']['name']: null;
or (with Laravel)
$name = isset($revision->data->name) ? $revision->data->name: null;
$name = isset($revision->data->name) ? $revision->data->name : 'default';
Is it safe in this specific case to use :
$value = @ $revision['data']['name'];
$value = @ $revision['data']['name'] ?: 'default';
If not, what would be a nicer way to handle these values ?
Thanks !
It's safe in the sense that it will prevent errors from reporting, however I wouldn't say it is good practice. It's more explicit when you see isset
over @
, mostly because the code is telling me up front that it's checking for if the array index is set.
Another alternative is to use Laravel's array_get
if you don't mind pulling in their helper functions. In this case, you'd have: $name = (array_get($revision, 'data.name')) ?: null;
as Laravel's helper will return null automatically for unset indexes. You can also manually set a default value array_get($array, 'foo.bar', 'default');
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments