Jump to content

Best way to filtering to only integers?


dannyb785

Recommended Posts

<?php

$var = 1235523;

$var2 = -245;

$var3 = 'apple';

var_dump( isInt($var) ); // boolean true
var_dump( isInt($var2) ); // boolean true
var_dump( isInt($var3) ); // boolean false

function isInt( $var ) {
$var = (string)$var;
if( ctype_digit($var) || ($var[0] == '-' && ctype_digit(substr($var,1))) )
	return TRUE;
return FALSE;
}

?>

  Quote

No, regex would be a waste. But, that function is pretty much useless since you can just as easily use (int) $var instead of calling the function. You've basically created a function that does something that already exists.

 

I get what you're saying, but I only made it a function so that if I discovered that the function had a flaw in it that I could easily change it and not have to manually change every time I did that action on every page.

 

And about casting/filtering: I just need to make sure that the specific input is an integer and convert it to an integer if it's not. So if it was "9 lbs" that the result would be '9', and similar

  Quote

  Quote

No, the manual tells you that. Floats are numeric, but they aren't integers.

 

So why not use is_int?

 

Because PHP is loosely-typed, and generally variables coming from outside sources will be a string.

 

It really depends how detailed you want your error reporting. Casting as an integer will close many potential attack vectors, but there's no way of knowing if the value being cast as an integer was actually an integer-equivalent prior to.

 

I think you're taking my post out of context though. I was responding directly to this

  Quote

@xyph isn't is_numeric() doing the same thing?

 

I should've made that more clear.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.