Is PHP @ safe for checking array values ?

Jérémie

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 !

jardis

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.

edited at
0

Comments

0 comments
Login to comment

Related

Checking if string contain values from an Array in PHP

PHP Checking multiple values in an array - the right way?

Checking the equality of all values in array in php

PHP array performance checking key existence vs checking values existence

Checking if a values from array exists in a second array in PHP

Reduce the use of foreach in array when checking null values php

Checking values for an array for every $i

Finding and checking values in an array in ReactJS

checking values within array of arrays

Checking the axis of array for zero values

Checking nan values in a numpy array

Is it safe not to use array_key_exists() when checking if an item is in the array?

Checking array's elements are in another array in PHP

Checking if an array within an array is empty/null in PHP

JS checking object/array for ALL highest values

Checking unique values in array using LinkedHashSet in java

Checking if a string contains values from a char array

Checking if values in a column are a superset of another array

Checking if items within mapped array share values

How to filter an array/object by checking multiple values

Faster code for checking repeated values in a JS array

checking an array of string objects for null values

Checking if XML values are in an AS3 array

JQ checking for values in an array given as a parameter

Checking if a group of values is inside a given array

Getting Check Box Values and Checking if They are in an Array

Checking if received JSON contains specific values in PHP

Why won't the values in my Array safe?

sorting, splitting, checking array with nested loop PHP