1

I have a working if/else on a SQL return. If it's empty I display a default.

<?php 
if($row['imagename']==='')
    {
        echo "placeholder.png";
    }
else 
    {
         echo htmlspecialchars($row['imagename'], ENT_QUOTES, 'UTF-8');
    } ?>

and I tried to put it all on one line i.e.

<?php ($row['imagename']==='') ? echo "placeholder.png";:echo htmlspecialchars($row['imagename'], ENT_QUOTES, 'UTF-8'); ?>

which fails.

Could someone clarify why it fails?

tia

chris loughnane
  • 2,648
  • 4
  • 33
  • 54

5 Answers5

9

Remove the semicolon and add the echo at the beginning.

<?php echo ($row['imagename']==='') ? "placeholder.png" : 
      htmlspecialchars($row['imagename'], ENT_QUOTES, 'UTF-8'); ?>
Yan Berk
  • 14,328
  • 9
  • 55
  • 52
6
<?php echo ($row['imagename']==='') ? "placeholder.png" : htmlspecialchars($row['imagename'], ENT_QUOTES, 'UTF-8'); ?>

You are using the ternary operator incorrectly

Cups
  • 6,901
  • 3
  • 26
  • 30
5

As a language construct, echo doesn't like to be in a ?: expression. Do this instead:

echo true ? 'foo' : 'bar';
deceze
  • 510,633
  • 85
  • 743
  • 889
  • ?? according to **vld** (at least at PHP version 5.3.10), the compiler emits exactly what I would expect and the same as `echo (true ? 'foo' : 'bar');` – TerryE Jul 27 '12 at 11:41
  • @TerryE ?? I do not understand what you're saying. "vld"? I'm saying `true ? echo 'foo' : echo 'bar';` does not work, which it doesn't on 5.3.13. – deceze Jul 27 '12 at 11:42
  • Sorry deceze, I misread your A. My bad and mindfart. +1 on yr ans. echo is a statement and not a function. BTW for other readers [vld](http://pecl.php.net/package/vld) is an opcode disassembler. – TerryE Jul 27 '12 at 19:26
2

It fails because it's meant to be used with expressions and not statements. Refer to php comparison operators under ternary operator.

By putting a ; at the end of your expressions you have made them into statements.

Refer to: Expressions and statements to understand the difference between the two.

ryuusenshi
  • 1,976
  • 13
  • 15
1

One difference between print and echo is that print has a value, while echo does not.

The construct:

$test ? planA : planB

chooses one of the values planA or planB, even if you no intention of using the result. Since echo has no value, it won’t work:

$test ? echo 'plan A' : echo 'plan B'; // <-- not working

If you want to use this simple syntax, just replace your echo statements with print statements.

$test ? print 'plan A' : print 'plan B'; // <-- should work
Manngo
  • 14,066
  • 10
  • 88
  • 110