douou6696 2012-06-02 20:24
浏览 62
已采纳

如何编写一个函数来检查变量是否已定义并且是一个数字?

In the past when I needed to check if a variable was set and also a number, I would do:

if( isset($_GET['var']) && is_numeric($_GET['var']) )

But I think that's kind of ugly, especially when I need to check a bunch of variables in the same if statement, so I made a function:

function setAndNum($var)
{
    if(isset($var) && is_numeric($var))
        return 1;
    else
        return 0;
}

The problem is that when I pass an undefined variable to the function, like this (supposing the variable in the GET array is undefined):

if( setAndNum($_GET['var']) )

I get the php error:

Notice: Undefined index: ...

So the whole purpose of the function is basically defeated (or half the purpose, at least ;) ).

One thing that confuses me is how the isset() function works, and why I can pass an undefined variable to it but not to my own function?

Is it possible to make my setAndNum() function work?

  • 写回答

7条回答 默认 最新

  • doujiazong0322 2012-06-02 20:28
    关注

    Your problem is with $_GET being an array. When you pass $_GET['var'] to your function, this array value is already looked up and used as an argument to the function. Therefore you cannot effectively check the presence of 'var' in $_GET from within this function. You could rewrite it a bit to make it work for array values, something like this:

    function setAndNum($key, $array)
    {
        if(array_key_exists($key, $array) && is_numeric($array[$key]))
            return 1;
        else
            return 0;
    }
    

    Then call it like this:

    if( setAndNum('var', $_GET) )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题