Check if variable is a number and positive integer in PHP?

后端 未结 6 1400
甜味超标
甜味超标 2021-01-24 06:11

For example, say:


How do I check if variable

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-24 07:00

    use ctype_digit but, for a positive number, you need to add the "> 0" check

    if (isset($_GET['p']) && ctype_digit($_GET['p']) && ($_GET['p'] > 0))
    {
      // the get input contains a positive number and is safe
    }
    

    in general, use ctype_digit in this way

    if (ctype_digit((string)$var))
    

    to prevent errors

提交回复
热议问题