Page 1 of 1

a way to tell if...is a number?

Posted: Thu Dec 06, 2007 12:15 pm
by hgmmy
Is there a way to tell if the value of a variable or what have you, is any number? here's a little more info to give you a better idea what I need. I have a form that returns a number that coincides with a user id, and I want a way to make sure that the value is a number as an extra security measure...

Posted: Thu Dec 06, 2007 12:29 pm
by Zoxive

Posted: Thu Dec 06, 2007 12:29 pm
by SBukoski
You could look at the is_int() function. That will tell you if the number is an integer or not.

Posted: Thu Dec 06, 2007 12:30 pm
by SBukoski
Zoxive wrote:

Code: Select all

$Val = (int) $Val; //Type Casting
http://www.php.net/manual/en/language.t ... ypecasting

is_numeric
is_int

etc..
For this purpose I would not use is_numeric as it will allow for a mjuch wider range than what one would normally associate with a userid. is_int is definitely the best way to go, in this case. :)

Posted: Thu Dec 06, 2007 3:37 pm
by Ollie Saunders
is_int() on it's own will always be false. All input comes as a string. If 0 is an invalid id in your database you can use:

Code: Select all

if ((int)$input !== 0) {
    // good
}

Posted: Thu Dec 06, 2007 3:42 pm
by VladSun

Posted: Thu Dec 06, 2007 3:46 pm
by SBukoski
ole wrote:is_int() on it's own will always be false. All input comes as a string.
Good point, and one I obviously overlooked...

Posted: Thu Dec 06, 2007 11:01 pm
by crystal ship

Code: Select all

$string = intval($string);
if ($string == 0){
echo "The given variable is not an Integer";
} else {
	echo "The given variable is an Integer";
}

Posted: Fri Dec 07, 2007 9:34 am
by jmut
ole wrote:is_int() on it's own will always be false. All input comes as a string. If 0 is an invalid id in your database you can use:

Code: Select all

if ((int)$input !== 0) {
    // good
}
that doesn't really matter much....as non existing number also is invalid. simple typecast to (int) is enought IMHO

Posted: Fri Dec 07, 2007 11:36 am
by hgmmy
So what would be best? This method:

Code: Select all

if ((int)$input !== 0) {
    // good
}
, this method ctype_digit
or this method:

Code: Select all

if ( $user_ID >= 1 ) {
    //Code to be done...
};
(Note the last method just occurred to me as I read through ya'lls posts)

Posted: Fri Dec 07, 2007 11:41 am
by feyd
hgmmy wrote:

Code: Select all

if ( $user_ID >= 1 ) {
    //Code to be done...
};
(Note the last method just occurred to me as I read through ya'lls posts)
Not very effective. To find out why, throw a bunch of stuff at it.

Posted: Fri Dec 07, 2007 11:46 am
by hgmmy
I'll just trust you in that it's not very effective, and scratch it off the list.

Posted: Fri Dec 07, 2007 4:33 pm
by hgmmy
jmut wrote:simple typecast to (int) is enought IMHO
What do you by typecast, jmut?