How to verify if $_GET exists?

前端 未结 7 1924
生来不讨喜
生来不讨喜 2020-12-02 21:59

So, I have some PHP code that looks a bit like this:


    The ID is 

    


         


        
7条回答
  •  眼角桃花
    2020-12-02 22:46

    You can use isset function:

    if(isset($_GET['id'])) {
        // id index exists
    }
    

    You can create a handy function to return default value if index doesn't exist:

    function Get($index, $defaultValue) {
        return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
    }
    
    // prints "invalid id" if $_GET['id'] is not set
    echo Get('id', 'invalid id');
    

    You can also try to validate it at the same time:

    function GetInt($index, $defaultValue) {
        return isset($_GET[$index]) && ctype_digit($_GET[$index])
                ? (int)$_GET[$index] 
                : $defaultValue;
    }
    
    // prints 0 if $_GET['id'] is not set or is not numeric
    echo GetInt('id', 0);
    

提交回复
热议问题