Check if the variable passed as an argument is set
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?
Solution
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.
Simply pass by reference and then do isset check:
function is_blank(&$var){
return !isset($var) || trim($var) == '';
}
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.
Use empty
. It checks whether the variable is either 0, empty, or not set at all.
if(empty($smth))
{
//code;
}
精彩评论