omega1
omega1

Reputation: 1052

Detect empty variable in PHP not working

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.

Upvotes: 2

Views: 92

Answers (3)

Steven
Steven

Reputation: 6148

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;

Upvotes: 1

NotGaeL
NotGaeL

Reputation: 8484

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

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

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.

Upvotes: 1

Related Questions