Forum Moderators: coopster

Message Too Old, No Replies

Checke if a value is a number

         

turbohost

8:13 pm on Jan 19, 2005 (gmt 0)

10+ Year Member



Hi Guys,

I want to write a little script that has to do the following :

if ($a == "a number"){
}else{}

How can I check if $a is a number (it can also be some sort of text but then I want to do the 'else' part.

Thx,
Turbo

Salsa

8:40 pm on Jan 19, 2005 (gmt 0)

10+ Year Member



There are a few ways you could do this. Maybe the simplest would be:

if ($a + 0!= 0) // it's an number

...adding 0 to $a will attempt to convert $a to a number, and if it can't be converted, $a+0 wil equal 0. In this case, $a might also contain some letter charachters, too, however--or $a might be equal to zero, which IS a number...

For more precision, you might also do something like:

if (preg_match('/^(\d+)$/',$a)) // it's an integer

If you want to allow for floats, you'd have to allow for a single decimal in the regex, too.

I hope this helps.

jusdrum

8:50 pm on Jan 19, 2005 (gmt 0)

willybfriendly

9:25 pm on Jan 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



also intval() and/or floatval()

WBF

dreamcatcher

9:44 pm on Jan 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Also, you can use the character class [[:digit:]]

$number = "123";

if (eregi("^[[:digit:]]+$", $number))
{
return true;
}
else
{
return false;
}

Salsa

9:58 pm on Jan 19, 2005 (gmt 0)

10+ Year Member



Exellent. It seemed like there ought to be at least one function for that, but I didn't even look, and I can't think of an occasion where I've needed that. Oh well, I probably will now!

willybfriendly

11:02 pm on Jan 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I can't think of an occasion where I've needed that.

Commonly used when filtering post and get data prior to processing.

$id=intval($_POST[id]);

WBF

coopster

1:38 pm on Jan 21, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I would just like to add something to the discussion regarding checking numeric input, specifically numbers only, no decimal points, no other punctuation. A common edit that works great is
if (isset($_POST['variable'])  
&& is_numeric($_POST['variable'])
&& is_int($_POST['variable'] + 0)
)
However, be careful with is_int()! Anything over 10 digits is no longer an integer, it's a float! That's when I have found it best to use a regular expression.
if (isset($_POST['variable']) 
&& is_numeric($_POST['variable'])
&&!preg_match('/[[:^digit:]]/', $_POST['variable'])
)