Home >Backend Development >PHP Tutorial >How Can I Convert a String to a Number in PHP?
Converting a String to a Number in PHP
Unlike JavaScript's Number() method, PHP lacks a direct function to convert strings to numbers. However, PHP allows for type coercion in various situations.
Type Casting for Explicit Conversion
In cases where explicit conversion is required, casting can be employed using the following syntax:
For instance, consider the following conversions:
$num = "3.14"; $int = (int)$num; // Result: 3 $float = (float)$num; // Result: 3.14
PHP's Automatic Type Coercion
In most instances, PHP will automatically coerce types during operations. For example:
$num = "2"; $total = $num + 10; // $total will be 12 (an integer)
The above is the detailed content of How Can I Convert a String to a Number in PHP?. For more information, please follow other related articles on the PHP Chinese website!