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

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

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: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: