dqiu dqiu - 4 months ago 7x
PHP Question

php null replacement function

there is this function called Nz() in visual basic for application. the function checks variable nullity and returns a provided value if it finds the variable is null.

i try to write the same function in php, which looks like below:

function replace_null($value, $replace) {
if (!isset($value)) {
return $replace;
} else {
return $value;

$address = replace_null($data['address'], 'Address is not available.');

of course, if
is found null, php will stop executing the code and
won't be called.

i'm currently using ternary

(isset(data['address']) ? data['address'] : 'Address is not available.');

but i think
, if it works, will offer a more convenient way.

is there a function in php that provide the same functionality as vba's Nz()?
any suggestion will be appreciated.

thanks in advance.


A bit roundabout: If you only use this to check for array members, you could pass the key separately:

function get_with_default($arr, $key, $defval)
  return isset($arr[$key]) ? $arr[$key] : $defval;

If the variable could be set but null (Edit: which it cannot, thanks @deceze), add another check:

function get_and_coalesce_with_default($arr, $key, $defval)
  return (isset($arr[$key]) && !is_null($arr[$key]) ? $arr[$key] : $defval;

As pointed out, isset() only succeeds on non-null values, so the above doesn't add anything. We can write a non-trivial check with array_key_exists, though:

function get_with_default_v2($arr, $key, $defval)
  return (array_key_exists($key, $arr) && !is_null($arr[$key]) ? $arr[$key] : $defval;