1

I am printing an image using an ID which is generated. however i wanted to do a check to see if this image exists and if it doesnt print no-image.jpg instead...

<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" /> 

It would be great if this could be kept on one line is possible. Any help would be appreciated.

Ether
  • 53,118
  • 13
  • 86
  • 159
Andy
  • 2,991
  • 9
  • 43
  • 62

3 Answers3

3

What Kristopher Ives says, and file_exists:

echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")

btw, your snippet is unlikely to work, as you seem to be combining plain HTML output and PHP without putting the PHP into <? ?>

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
3

My recommendation would actually be to abstract the decision making from the html tag itself, in a separate block of php logic that is not outputting html...here is an abbreviated example that assumes you are not using a template engine, or MVC framework.

<?php
$filename = 'th.jpg';
$filePath = '/public/images/' . $row['id'] '/';
$webPath  = '/images/' . $row['id'] . '/'; 
//Logic to get the row id etc
if (!file_exists($filePath . $filename)) {
    $filename ='no-image.jpg';
    $webPath  = '/images/';
}
?>
<img src="<?php echo $webpath . $filename;?>" />
JC.
  • 670
  • 3
  • 12
  • I forgot to explain why :P In this case it seperated your business logic from your presentation logic, allowing you to uther abstract it later on, should you use a framework or decide to restructure your code, and calls out the logic for determining which source path to use from the logic of actually displaying it, and keeps the interspersed php code in your html to a minimum. – JC. Dec 30 '09 at 22:31
  • This is very detailed, thanks. Ill do this for future versions and i can definately see the benefits. Thanks again! – Andy Dec 30 '09 at 22:45
2

Wow, this question gets asked and answered a lot:

http://en.wikipedia.org/wiki/Ternary_operation

You could do it by:

<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >
Kristopher Ives
  • 5,838
  • 7
  • 42
  • 67