How to parse an integer in PHP?

I can use intval , but as per the documentation:

Lines are likely to return 0, although this depends on the leftmost characters of the line. General casting rules apply.

... and the value for parsing can be 0 , that is, I can not distinguish zero from a string .

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

The real question is: how can I parse a string and distinguish between a string that is different from 0 and zero itself?

+6
source share
2 answers

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

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

I did not compare with ctype_digit (), but I think this is a good option. Of course, it depends on the exact behavior that 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 
0
source

All Articles