This article demonstrates how to convert a numeric string to a number in PHP 8.

1. Using Casting

You can convert a string to a numeric type by explicitly casting the string. For example, the following casts a string to an integer:

Download  Run Code

 
You can convert a numeric string to other primitive data types as well. For example, the following casts a string to a float:

Download  Run Code

2. Using + operator

A better option is to simply add zero to the string, which automatically converts the string to an int or float as appropriate. This eliminates the need to check if the string is an int or float before casting.

Download  Run Code

 
Alternatively, you can use the identity arithmetic operator to convert a numeric string to an int or float. The expression +$s will convert the string $s to the corresponding int or float, as demonstrated below:

Download  Run Code

3. Using intval() and floatval() function

PHP provides the built-in function intval() to get the integer value of the specified variable. You can convert a string to an int using this function, as follows:

Download  Run Code

 
To get the float value of the specified variable, you can use the built-in function floatval(). The following code uses it to convert a string to a float:

Download  Run Code

 
It should be noted that both intval() and floatval() might perform slower than the casting and addition/identity arithmetic operators discussed before.

That’s all there is to converting a numeric string to a number in PHP 8.