开发者

if statement on one line if poss

I am printing an image using an ID which is generated. however i wanted to do a check to se开发者_开发知识库e 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.


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 <? ?>


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;?>" />


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'; ?> >
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜