You can use the function isset
, however there is one however if the assigned value 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
Note that the property exists but the result was negative. This is because the function isset
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.
if(isset($obj->operacao->nome)){ ... }
?– usuario
It worked, thank you.
– Hugo Borges