0
votes

I provided code, where first argument is path to image or default NULL in MySQL database,

function formatImage($img = NULL, $alt = NULL)
    {
        // if(isset($img)) DOESN'T WORK
        if(!$img == NULL)
        {
            return '<img src="' . $img . '" alt="' . $alt .'" />';
        }
        else
        {
            return NULL;
        }
    }

Why isset doesn't work? Instead I have to check if is (!$img == NULL).

In case of using checking argument with isset, and that $img is NULL in database. as output im getting whole HTML IMG tag with empty src attibutes, and alt attribute which is actaully title fetched from database. Setting display property to none to images without src attribute isn't acceptable.

2
Define: DOESN't WORK - Mosty Mostacho
Perhaps $img ends up containing a string 'NULL' - so his approach to using isset() didn't work out that well. - SquareCat
@MostyMostacho See edit. - Alan Kis
I'm pretty sure a var_dump($img) just before the if will shed some light here - Mosty Mostacho

2 Answers

2
votes

Try this:

if($img != NULL) {
    return '<img src="' . $img . '" alt="' . $alt .'" />';
}

Explanation:

If you compare !$img against NULL you basically do a boolean reversal on $img and then seeing if that compares to NULL - which is not what you want.

Also, please note that you should use

if($img !== NULL)

instead. != will compare the values of the variables provided, while !== will compare the values AND the datatype (which in case of NULL might be your best interest).

0
votes

After checking variable with var_dump, returned data from database is actually empty string,

string(0) "" and not `NULL` datatype and value literally.

That's why isset() keep returning TRUE in both cases. Using value checking works fine, because returned value is empty string not NULL data object, I mean type.

From php.net for return values of ISSET language construct:

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

Checking returned variable value and datatype against NULL would both evaluates to false, in case of !== true because datatype is NOT NULL as value IS NULL.

Seems that problem was in fact that I have expected NULL in database field behave as NULL data type.

Please correct me if I thinking wrong.

+1 @SquareCat