PHP: Check if variable exist but also if has a value equal to something

前端 未结 13 1717
抹茶落季
抹茶落季 2020-12-01 13:46

I have (or not) a variable $_GET[\'myvar\'] coming from my query string and I want to check if this variable exists and also if the value corresponds to somethi

13条回答
  •  独厮守ぢ
    2020-12-01 14:17

    I use all time own useful function exst() which automatically declare variables.

    Example -

    $element1 = exst($arr["key1"]);
    $val2 = exst($_POST["key2"], 'novalue');
    
    
    /** 
     * Function exst() - Checks if the variable has been set 
     * (copy/paste it in any place of your code)
     * 
     * If the variable is set and not empty returns the variable (no transformation)
     * If the variable is not set or empty, returns the $default value
     *
     * @param  mixed $var
     * @param  mixed $default
     * 
     * @return mixed 
     */
    
    function exst( & $var, $default = "")
    {
        $t = "";
        if ( !isset($var)  || !$var ) {
            if (isset($default) && $default != "") $t = $default;
        }
        else  {  
            $t = $var;
        }
        if (is_string($t)) $t = trim($t);
        return $t;
    }
    

提交回复
热议问题