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

前端 未结 9 1598
北恋
北恋 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题