2

I thought that the filter_input(type, name, FILTER_SANITIZE_NUMBER_INT) will convert the string to int but it seems it does not.

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

if (isset($id) && is_int($id))

Is there another clean but working way to do this?

Chazy Chaz
  • 1,781
  • 3
  • 29
  • 48
  • your first if statement will always default to true because your already defining the $id variable see my other comment – Mujnoi Gyula Tamas Nov 10 '15 at 14:36
  • So I just check for `is_int()`? Ok thanks I'm using the ternary operator you made. No need to filter/sanitize? – Chazy Chaz Nov 10 '15 at 15:48
  • no need to further sanitize since if you are getting an id in the GET then it will be typecasted to integer, so what you will need to do is check if $id is bigger than 0 if( $id > 0 ){ /* do stuff */ } – Mujnoi Gyula Tamas Nov 10 '15 at 16:05

3 Answers3

4

You can always just cast it:

$id = (int) $_GET['id'];
wogsland
  • 9,106
  • 19
  • 57
  • 93
3

You can convert a string to an integer in various ways:

$id = (int)$_GET['id']; // Like wogsland showed.
$id = intval($_GET['id']); // This works but is around twice as slow as (int).

Here are some tests that I found, comparing the two: Fastest way to convert string to integer in PHP

Community
  • 1
  • 1
Audite Marlow
  • 1,034
  • 1
  • 7
  • 25
1

Casting to int via (int)$_GET['id'] seems to be the fastest option. You can also use is_numeric() to check if the string is numeric.

Beware that filter_var can return the boolean value false on failure, which will be evaluated as the integer 0.

You can read more about string conversion in the manual.

A warning from the manual: Booleans, floating point numbers and strings can be converted but the behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice!

Philipp Palmtag
  • 1,310
  • 2
  • 16
  • 18