2

I have been fighting with the following code and variants, but have not been able to come up with anything that works. The idea is that I detect if the variable $largeimg6 (the URL of an image) is empty or not (whether an image has been loaded) and if not, load the value of a default variable ($defaultimage) which holds the URL of a default image..

<?php if(!empty($largeimg6)) : ?>
<img class="rpPicture" id="rpPicture<?php echo $key; ?>" onload="showPicture(this, <?php echo SHOW_PICTURES; ?>)" width="60" height="60" src="<?php echo $largeimg6; ?>" alt="Buy CD!" title="Buy CD!" />
<?php endif; ?>

The problem is that I do not know where to add the arguement for $largeimg6 being empty and therefore adding:

$largeimg6 = $defaultimage

Any help would be appreciated.

Thanks.

4
  • Have you tried is_null() or isset()? Commented Oct 14, 2013 at 16:55
  • Where is $largeimg6 initially set? Will isset (php.net/manual/en/function.isset.php) work for you? Commented Oct 14, 2013 at 16:55
  • if (isset($myvar)&&strlen($myvar)>0) Commented Oct 14, 2013 at 16:55
  • Thank you for responding, I have resolved this. Commented Oct 14, 2013 at 17:12

3 Answers 3

1

You can try this before that if statement:

<?php $largeimg6 = $largeimg6 != '' ? $largeimg6 : $defaultimage; ?>

The != '' comparision may be change according to your need to isset(), strlen(), is_null()(as Ville Rouhiainen suggested) or whatever.

Sign up to request clarification or add additional context in comments.

1 Comment

@omega1 nice, glad to help!
1

You can use the alternative (and trim as already suggested):

$largeimg6 = trim($largeimg6);
if (isset($largeimg6)&&strlen($largeimg6)>0)

but you'll probably be doing better by filtering the url:

$largeimg6 = trim($largeimg6);
if(filter_var($largeimg6, FILTER_VALIDATE_URL))

More info: http://php.net/manual/es/book.filter.php

Comments

1

Solution

This answer assumes that you have a variable $largeimg6 which is either going to be set to a url or be empty.

That being the case it's a fairly simple fix. You need to remove the if statement entirely and replace your:

<?php echo $largeimg6; ?>

with:

<?php echo (empty($largeimg6)) ? '/default/image.jpg' : $largeimg6; ?>

Explanation

The above is equivalent to:

if(empty($largeimg6)){
    echo '/default/image.jpg';
}
else{
    echo $largeimg6;
}

But in the form:

(IF) ? THEN : ELSE;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.