How to check whether a variable in $_GET Array is an integer?

前端 未结 9 1506
北恋
北恋 2020-12-10 20:46

I have a page like so:

http://sitename/gallery.php?page=2

It has pagination links at the bottom by which we can br

相关标签:
9条回答
  • 2020-12-10 21:17
    if(!empty($_GET['page']) and is_numeric($_GET['page'])){
           $page = (int)$_GET['page'];
           echo "Page Number: ".$page;
    }
    

    is_numeric is probably what you need.

    0 讨论(0)
  • 2020-12-10 21:23

    Use is_numeric().

    is_int() will not work because GET parameters are always string.

    0 讨论(0)
  • 2020-12-10 21:26

    Using filters:

    if (null !== ($page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE))) {
        // $page is now an integer
    }
    

    This also checks whether the variable appears in the query string at the same time. If you want to differentiate between missing and invalid you have to leave off the last argument to filter_input():

    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    // $page can be null (not present), false (present but not valid) or a valid integer
    
    0 讨论(0)
  • I've left a few comments here and there. Thanks to weak typing, functions like empty and isset tend to be unreliable. The quickest way to check if a parameter is an int or not IMO would be this:

    if (array_key_exists('page',$_GET) && ($_GET['page'] == (int) $_GET['page']))
    

    Casting to int and then compare the respective values will return true only when $_GET['page'] is a valid int. If you want to use strict type comparison for some reason (some do), you could double cast:

    if (array_key_exists('page',$_GET) && ($_GET['page'] === (string)((int) $_GET['page'])))
    

    But in this particular case, I can't really see why you would want to do that

    0 讨论(0)
  • 2020-12-10 21:27

    this is a way how to check parameter if it is intetger or not.

    if (is_int((int) $_GET['user_id']) && (int) $_GET['user_id'] != 0) {
        $user_id = $_GET['user_id'];
    }
    
    0 讨论(0)
  • 2020-12-10 21:28

    You can also check with

    isNAN($_GET['something']);//is_numeric($_GET['something'])
    

    it returns a boolean value(true,flase)....if its true then it is not an integer,if false its an integer.

    0 讨论(0)
提交回复
热议问题