Skip to content
Advertisement

How to check if property is defined and provide a substitute in PHP?

My service sometimes returns

$business->price

set and sometimes not and my code

$feature['properties']['price'] = $business->price;

throws error

Undefined property: stdClass::$price'

in that case.

What is the shortest way to check if property set and if it is, then return it’s value, but if it isn’t then return some predefined value like 0 or NULL?

Advertisement

Answer

Ternary operator,if it`s not set the price will be 0

$feature['properties']['price'] = $business->price ? $business->price : 0;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement