Foo Bar
Foo Bar

Reputation: 1892

Is it safe to concatenate `null` with a string in PHP?

I didn't found a statement about the compatibility between strings and null in the docs, but trying this on PHP 5.5:

echo 'foo' . null . 'bar';

prints out foobar.

I wonder if this behaviour is guaranteed, or "safe" to do (in SQL, for example, it is not)? Or asking the other way: Would I ever need to check for null before concatenating strings? Like

echo 'foo' . (($mystring === null) ? '' : $mystring) . 'bar';

Upvotes: 40

Views: 13308

Answers (1)

user3942918
user3942918

Reputation: 26375

From the documentation:

NULL is always converted to an empty string.


Yes, you can rely on that behavior.

Upvotes: 60

Related Questions