sergey sergey - 4 months ago 38
PHP Question

Echo null values in PHP

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

<?php
echo $a;


But if set null, we get empty string?
http://sandbox.onlinephpfunctions.com/code/602702f85a54ec4b42bfff22ca25127c4a4c9ace

<?php
$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?

<?php
echo $a ?: '';


Thanks

Answer

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.