doushifang4382 2010-08-23 11:17
浏览 38
已采纳

检查是否设置了作为参数传递的变量

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.

  • 写回答

3条回答 默认 最新

  • duanchuopi2298 2010-08-23 11:26
    关注

    Simply pass by reference and then do isset check:

    function is_blank(&$var){
        return !isset($var) || trim($var) == '';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 Python如何后台操作Vmwake虚拟机键鼠
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容