gremo
gremo

Reputation: 48909

How to correctly parse an integer in PHP?

I can use intval, but according to the documentation:

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

... and the value to parse can be 0, that is I will not able to distinguish between zero and a string.

$value1 = '0';
$value2 = '15';
$value3 = 'foo'; // Should throw an exeption

Real question is: how can I parse the string and distinguish between a string that cast to 0 and a zero itself?

Upvotes: 16

Views: 13923

Answers (2)

donquixote
donquixote

Reputation: 5471

I have not benchmarked against the ctype_digit(), but I think the following is a nice option. Of course it depends on the exact behavior you expect.

function parseIntOrException($val) {
  $int = (int)$val;
  if ((string)$int === (string)$val) {
    throw \Exception('Nope.');
  }
  return $int;
}

http://3v4l.org/Tf8nh

1       1
'2'     2
'3.0'   false
4.0     4
5       5

Upvotes: 0

user142162
user142162

Reputation:

In the code below, $int_value will be set to null if $value wasn't an actual numeric string (base 10 and positive), otherwise it will be set to the integer value of $value:

$int_value = ctype_digit($value) ? intval($value) : null;
if ($int_value === null)
{
    // $value wasn't all numeric
}

Upvotes: 18

Related Questions