I think for your specific example, you would access the error with $arr[0]->Error
but the assoc options in json_decode means that it depends on what you asked json_decode
to do.
Which means if you did $arr = json_decode($json, true)
, then you would access the error with $arr[0]['Error']
because the JSON will then always decode objects into an associative arrays.
This is a lovely example of mutation and confusion with JSON and PHP, it's possible that you start with an associative array in PHP, convert it to JSON and back and lose the associative array. Just something to keep an eye on.
In PHP, you access arrays with [
square brackets ]
and object properties with ->
the arrow. They're not interchangeable like the bracket and dot notations in JavaScript. So you always need to be mindful of whether your data structures are objects, or associative arrays.
As for testing if the propery exists, you use isset:
if(isset($arr[0]->Error)) {
// handle error
}
Now, I really hate using isset everywhere, so I have a utility function:
function getProperty($object, $propertyName, $defaultValue = false)
{
$returnValue = $defaultValue;
if (!empty($object)) {
if (is_array($object)) {
if (isset($object[$propertyName])) {
$returnValue = $object[$propertyName];
}
} else {
if (isset($object->$propertyName)) {
$returnValue = $object->$propertyName;
}
}
}
return $returnValue;
}
Which means in my code, I do:
if(($error = getProperty($arr[0], 'Error')) === false) {
// process $error
}
... but that was borne out of always wanting uninitialised values be given default values when they didn't exist, most of the time. (The function is so big because it also works on objects and arrays)