views:

61

answers:

3

I want to check if a variable called $smth is blank ( i mean empty space ), and i also want to check if it is set using the function i defined below:

function is_blank($var){
    $var = trim($var);
    if( $var == '' ){
        return true;
    } else {
        return false;
    }
}

The problem is i can't find a way to check if variable $smth is set, inside is_blank() function. The following code solves my problem but uses two functions:

if( !isset($smth) || is_blank($smth) ){
    // code;
}

If i use an undeclared variable as an argument for a function it says:

if( is_blank($smth) ){
    //code;
}

Undefined variable: smth in D:\Www\www\project\code.php on line 41

Do you have a solution for this ?

Thank you very much, Alex from Romania

** !! LATER EDIT !! **

This is what i came up with:

function is_blank(&$var){ 
    if( !isset($var) ){ 
        return true; 
    } else { 
        if( is_string($var) && trim($var) == '' ){ 
            return true; 
        } else { 
            return false; 
        } 
    } 
}

and works like a charm, thank you very much for the idea nikic.

A: 

Use empty. It checks whether the variable is either 0, empty, or not set at all.

if(empty($smth))
{
    //code;
}
shamittomar
Doesn't handle " "
Bobby Jack
i know, that's why i didn't used it
Alexandru
A: 

Whenever you use a variable outside of empty and isset it will be checked if it was set before. So your solution with isset is correct and you cant' defer the check into the is_blank function. If you only want to check if the variable is empty, use just the empty function instead. But if you want to specifically check for an empty string after a trim operation, use isset + your is_blank function.

chiborg
thank you very much chiborg
Alexandru
-1 wrong. If passing by reference it doesn't apply.
nikic
+4  A: 

Simply pass by reference and then do isset check:

function is_blank(&$var){
    return !isset($var) || trim($var) == '';
}
nikic
How about "return !isset($var) || !trim($var);" ?
Bobby Jack