The filter_var() function is the right tool for the job here.
Here's a filter that will return invalid only for unsigned integers or unsigned integers:
$filteredVal = filter_var($inputVal, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)));
Here is the filter documentation .
Example:
<?php $testInput = array( "zero string" => "0", "zero" => 0, "int" => 111, "string decimal" => "222", "empty string" => "", "false" => false, "negative int" => -333, "negative string decimal" => "-444", "string octal" => "0555", "string hex" => "0x666", "float" => 0.777, "string float" => "0.888", "string" => "nine" ); foreach ($testInput as $case => $inputVal) { $filteredVal = filter_var($inputVal, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0))); if (false === $filteredVal) { print "$case (". var_export($inputVal, true) . ") fails\n"; } else { print "$case (". var_export($filteredVal, true) . ") passes\n"; } }
Output:
zero string (0) passes zero (0) passes int (111) passes string decimal (222) passes empty string ('') fails false (false) fails negative int (-333) fails negative string decimal ('-444') fails string octal ('0555') fails string hex ('0x666') fails float (0.777) fails string float ('0.888') fails string ('nine') fails
source share