Archive

Posts Tagged ‘string to int’

Accept positive integers only (string to int) [PHP]

November 26, 2010 Leave a comment

Problem

You have a form and in a field you want to accept positive integers only. However, in PHP the conversion from string to int is a bit strange:

$a = "1.3";
print (int)$a;		// => 1, no error
$a = "7 sins";
print (int)$a;		// => 7, no error
$a = "0";
print (int)$a;		// => 0
$a = "hello";
print (int)$a;		// => 0 again (Did we convert "0", or is it an error? We don't know.)

There is no exception raised if the input couldn’t be converted correctly.

Solution

if (!( is_numeric($val) and ((string)(int)$val === (string)$val) and ((int)$val > 0) )) 
{
    // not a positive integer
}

Read it like this: (a) $val must be numeric, and (b) the string $val must be converted into the same integer number, and (c) $val must be positive. If it’s not true (see the negation (!)), then $val is not a positive integer.

Credits

Inspired by a comment here.

Categories: php Tags: ,