How to echo a variable that I don't know is set or not in an easy to read way in PHP -


just have simple question. think know answer hope not.

i want able echo out variable don't know whether set or not. want default variable if not set , don't want have check if set first.

so here example:

i have $variable don't know whether set or not.

then

echo "this number: " . $variable; 

if $variable set 5, want print "this number: 5" , if not set, want print "this number: 0".

i know this:

echo "this number: " . ($variable? : 0); 

but still notice saying $variable undefined, though echo displays correctly.

i this

if (!isset($variable))  {   $variable = 0); } echo "this number: " . $variable; 

but that's code if i'm doing lot.

the null coalescing operator new best friend.

echo "this number: " . ($variable ?? 0); 

the null coalescing operator available of php 7.0.0. alternative, use in older versions right php 5.3.0, use isset() , ternary operator ?:.

echo "this number: " . (isset($variable) ? $variable : 0); 

Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -