sergey sergey - 1 year ago 184
PHP Question

Echo null values in PHP

If we are do not define variable, we get notice, for example

echo $a;

But if set null, we get empty string?

$a = null;
echo $a;

$str = DB::find()->select('name')->where(['id' => 1])->one(); //returns null or string name

echo $str;

Is it normal practice use this approach for returned values from DB or some function or this is undocumented feature?

Or better handle vars like this?

echo $a ?: '';


Answer Source

PHP has a feature known as "type juggling", where when a function is called on some data that is unsupported, PHP will try to convert the data to a usable format. For example, echo 1234; will output 1234, rather than throwing an error (as 1234 is not a string).

Now, null is type juggled to the empty string, as it's probably the most logical thing for it to convert to (null representing the concept of nothing). This behaviour is defined here, under the converting to string section.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download