Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is made up of integers in PHP

Tags:

php

I am writing php code to validate some data entered by the user, one of them is an integer, I used $_REQUEST["age"] to get it, when I'm checking if this value is integer with gettype($_REQUEST["age"] == "integer" and is_int($_REQUEST["age"]) both give me false, but when I use is_numeric($_REQUEST["age"]) is gives me true. I want to check if the value of the parameter is an integer or not, am I using the first 2 functions correctly or am I missing something?

Thakns

NOTE: I tried to output gettype($_REQUEST["age"]) it gives me string

like image 859
hakuna matata Avatar asked Oct 21 '25 04:10

hakuna matata


1 Answers

Short version:

Use ctype_digit($_REQUEST['age'])

Long version:

Your problem, as you've found when you use gettype, is that $_REQUEST returns a string. Even if that string is an integer semantically, like 16, it would still be a string-type and not an integer-type variable. You're getting different results from the two tests because they test different things:

  • is_numeric tests whether a string contains an "optional sign, any number of digits, optional decimal part and optional exponential part" according to the PHP docs. In your case, the string does only contain digits, so the test returns True.
  • is_int tests whether the variable's type is an integer - which it won't be, because it's being returned by $_REQUEST.

That's why is_numeric returns True while is_int returns False: the string only contains numbers (and so "is numeric") but still technically has a string type, not an integer type (and so "isn't an int"). Of course, is_numeric isn't sufficient for integer testing, because it will return True if the string has a decimal or uses scientific notation, i.e. is numeric but not an integer.

To test if the $_REQUEST is an integer, regardless of technical type, you can test whether all the characters in the string are digits (and thus the string as a whole is an integer). For this you can use ctype_digit:

ctype_digit($_REQUEST['age'])

This will return True for 16 but not for 16.5 or 16e0 - weeding out the integers from the numeric non-integers.

like image 60
ASGM Avatar answered Oct 23 '25 17:10

ASGM