Home > Software design >  PHP echo $foo ? 'bar' without the false part?
PHP echo $foo ? 'bar' without the false part?

Time:11-05

Is there any way to write this

echo $foo ? 'bar' : '';

but without the false part? Just like this:

echo $foo ? 'bar';

and nothing would be echoed if $foo is false automatically?

I often find that I just want to echo something if it's true but don't care about an else statement :)

CodePudding user response:

You could write your own function to do this:

function when($returnContent,$content)
{
  return $returnContent ? $content : '';
}

That is simple enough, you can use it like this:

echo 'text before ' . when($foo, 'middle text ') . ' text at end.';

Perhaps not what you had in mind, but it does the job.

CodePudding user response:

This won't work with echo, but using print() your can do:

$foo && print('bar');

I just discovered that parentheses aren't even needed for print, so a bit shorter would be:

$foo && print 'bar';

Please also note @IMSoP's striking comment below, about parentheses for echo and print:

Note also that neither echo nor print is a function, and using parentheses like you have here is a habit to avoid, as it can sometimes be misleading - e.g. print('hello') && true; will output "1", not "hello" - the parentheses mean nothing, and the value passed to print is the result of 'hello' && true

  •  Tags:  
  • php
  • Related