views:

187

answers:

3

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.

+1  A: 

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
I think he might have been asking more about how to check and see if the image was available.
Topher Fangio
yeh, but that was useful too :)
Andy
Oh, indeed, I was kinda in auto-mode hehe
Kristopher Ives
Thats cool, thanks mate!
Andy
+3  A: 

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
it is wrapped in php but thanks for the note...
Andy
+3  A: 

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
I forgot to explain why :PIn 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
This is very detailed, thanks. Ill do this for future versions and i can definately see the benefits. Thanks again!
Andy
Very good point.
Pekka