Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in PHP.
To run the program, save it as number-parsing.php and use php:
In PHP:
We use floatval() to parse floating-point numbers. It doesn’t require specifying precision like in some other languages.
intval() is used for parsing integers. It can handle different bases, including hexadecimal.
There’s no separate function for parsing unsigned integers in PHP. intval() is used for both signed and unsigned integers.
PHP doesn’t have a direct equivalent to Atoi, but intval() serves the same purpose for base-10 integer parsing.
Unlike some other languages, PHP’s parsing functions typically return 0 for invalid input rather than throwing an error. You may need to use additional checks if you need to distinguish between a valid zero and an error condition.
Next, we’ll look at another common parsing task: URLs.