What's the best way of checking that a variable only has numbers in it, so no letters or commas etc.
Printable View
What's the best way of checking that a variable only has numbers in it, so no letters or commas etc.
Use the is_numeric function.
If its from an imput form or something that's going to be a little but "less then perfect", you might want to do some cleanup to remove trailing spaces etc. (trim)PHP Code:<?php
$var1= "12three"; // alphanumeric
$var2 = "123"; // numeric string
$var3 = 123; // integer
if(is_numeric($var1))
{
echo "this will not be echo'd because it is false";
}
if(is_numeric($var2))
{
echo "this will be echo'd because it is true";
}
if(is_numeric($var3))
{
echo "this will be echo'd because it is true";
}
?>
thnx for the reply, i'll give it a go.
It seems there's no need to do a Trim for an input form, bonus!!!
Thnx again.
careful as is_numeric will also detect this as numeric
4e4 and 444 // those are both correct.
you want this
Code:if (preg_match ("/^([0-9]+)$/", $input_number)) {
echo "true";
} else {
echo "false";
}