Home > front end >  echo varialbe nor placeholder if variable doesn't exist
echo varialbe nor placeholder if variable doesn't exist

Time:12-19

I tried this:

echo $open_hour ?? 20;

Result:

20

But If I try this:

echo "My text ".$open_hour ?? 20;

Resul:

"My text"

Where is my mistake?

CodePudding user response:

The use of brackets will show you what the PHP compiler is seeing.

Your first example is:

echo ($open_hour) ?? (20);

Which is saying...

Print the value of $open_hour unless it's null/undefined, then print 20. As $open_hour is null/undefined, it prints 20.

Your second example is:

echo ("My text ".$open_hour) ?? (20);

or, print the value of "My text $open_hour", unless $open_hour is null/undefined, then print 20.

This isn't what you're intending; so you need to use brackets.

echo "My text ".($open_hour ?? 20);
  •  Tags:  
  • php
  • Related