You can use the isset
function, however there is a however if the value assigned is null:
<?php
$json = '{
"operacao": {
"nome": "João"
}
}';
$obj = json_decode($json);
if( isset( $obj->operacao->nome ) ){
echo "Existe a propriedade";
} else {
echo "Não existe a propriedade";
}
//resultado: Existe a propriedade
But the property can exist but with a null value, for example:
$json = '{
"operacao": {
"nome": null
}
}';
//resultado: Não existe a propriedade
Notice that the property exists but the result was negative. This is because the isset
function determines whether the variable has been defined and is not null.
In this case use the function property_exists
:
if( property_exists( $obj->operacao, 'nome' ) ){
echo "Existe a propriedade";
} else {
echo "Não existe a propriedade";
}
//resultado: Existe a propriedade
In the case of the function property_exists
is checked only if the property exists and the value assigned is not considered.