June 26, 2012

How to set this if isset function

Question by Danny Florian

I have the following code that sets a background if user has uploaded to database. If user has NOT uploaded an image then the result is a blank img src=”

I need to set this as an if isset function so I can plug in an alternate image if user has not uploaded anything.

Here is the current code:

<div id="background"><?php echo isset($background_image) && file_exists(ROOT.$background_image)?"<img src='$background_image' alt='' />":'';?></div>

Answer by Eoghan

Your code’s a little dirty, opening php and closing it mid-html tag is only going to make it confusing for you in the future.

You’re echoing back an isset which is just echo’ing back a boolean.

Try this;

$background_image = ""; // Not sure what you're using here - their username? Dump it in here anyway.
if (file_exists($background_image))
    echo "  <div id="background">
            <img src="{$background_image}" alt="" title="" />

Hope this helps.

  • Eoghan

Answer by Starx

Is it really neccessary to set the blank source of the image?

But a understandable and corrected code of what you are attempting is this

<div id="background">

    echo "<img src='"; 
        echo isset($background_image) && file_exists(ROOT.$background_image) ? $background_image : '';
    echo "' alt='' />";


The problem was that, either you were echo entire <img> tag, or just display ' '(Blank) with attached endings.

The short form:

    echo "<img src='".(isset($background_image) && file_exists(ROOT.$background_image) ? $background_image : '')."' alt='' />";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!