PHP Validation Numbers Only From

Bookmark and Share

How to check for number values only and block or convert letter strings to integers.

Question: How to validate number values to and block all letters and symbol in a form.

Answer: You can check the value or convert the value to an integer (number).

1) Check a value using is_int() to finds whether the given variable is an integer

<?
if(is_int($variable))
echo "Pass test";
else
echo "Please use only numbers";
?>

2) Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

<?
if(is_numeric($variable))
echo "Pass test";
else
echo "Please use only numbers";
?>

3) Convert the value to an integer (number) using settype.

<?php
$foo = "5bar"; // string
$bar = true; // boolean

settype($foo, “integer”); // $foo is now 5 (integer)
settype($bar, “string”); // $bar is now “1″ (string)
?>

or you can use int to do the trick.


<?
$int=593; // $int is a integer
$int.=""; // $int is now a string
?>

Please rate this post by clicking a star:

(11 votes, average: 3.27 out of 5)

No Responses to “PHP Validation Numbers Only From”

  • is_numeric has problem

    just input 345345e45 watch "e" in the middle w' means power i think it accept this as an i/p of numbers

    thanks.

Leave a Reply





Tags: , , , , , , , ,