PHP functions to validate Integer, Float and characters length input

Sometimes we need to validate an input from client browser before we push the value into further proccess, here i share 3 simple functions to perform validation input from forms and or querrystrings

Validate Integer Value Using isNumeric function

function isNumeric($n){
return ( $n == strval(intval($n)) )? true : false;
}

the simple php function above will perform an integer validation input, the proccess is pretty simple, the if control structure will evaluate whether the argument value ($n) has the same type with itself after cast to integer (strval(intval($n))), the right part of if expression (strval(intval($n))) is a simple way to cast any type of variable into integer. Sample of usage:

echo ‘<br />isNumeric(1) = ‘.(string)isNumeric(1);
echo ‘<br />isNumeric("a") = ‘.(string)isNumeric(‘a’);
echo ‘<br />isNumeric(0.1) = ‘.(string)isNumeric(0.1);

Validate Float Value Using isFloat function

function isFloat($n){
    return ( $n == strval(floatval($n)) )? true : false;
}

the simple php function above has same proccess with isNumeric function the difference is only the second part of if expression (strval(floatval($n))) which has function to cast the value of argument into floating point variable. Sample of usage:

echo ‘<br />isFloat(1) = ‘.(string)isFloat(1);
echo ‘<br />isFloat("a") = ‘.(string)isFloat(‘a’);
echo ‘<br />isFloat(0.1) = ‘.(string)isFloat(0.1);

Validate Characters Length Using isLength function

function isLength($s,$min,$max){
    $curLength = strlen($s);
    return (($curLength >= (int)($min)) && ($curLength <= (int)($max)))? true : false;
}

the php function above will perform a Length of characters validation, it takes 3 arguments which are (string_to_be_validate,minimum_length,maximum_length). Sample of usage:

echo ‘<br />isLength("aku",1,4) = ‘.isLength(‘aku’,1,4);
echo ‘<br />isLength("aku",4,4) = ‘.isLength(‘aku’,4,4);
echo ‘<br />isLength("aku",3,4) = ‘.isLength(‘aku’,3,4);

2 Responses to “PHP functions to validate Integer, Float and characters length input”


  1. 1 Caio C Iglesias

    My results were:

    isNumeric(1) = 1
    isNumeric(”a”) =
    isNumeric(0.1) =

    isFloat(1) = 1
    isFloat(”a”) =
    isFloat(0.1) = 1

    isLength(”aku”,1,4) = 1
    isLength(”aku”,4,4) =
    isLength(”aku”,3,4) = 1

    Shouldn’t it be outputing true or false?

  2. 2 Caio C Iglesias

    Ahhh, you have to use ‘true’ and ‘false’ with the apostrophes.