How do I convert a string to a number in PHP?

The easiest way to convert strings to numbers in PHP is to use the (int/float/double)$variable cast, which directly converts the string to a number. You can also convert a string to a number using the intval(), floatval(), number_format() and settype() functions. The intval() function converts a string to an integer, and the floatval() function converts a string to a floating-point value. The number_format() function converts a string to a number and returns the formatted number on success; if it fails, the function throws an "E_WARNING" error. The settype() function is used to set or change the type of an existing variable. In this PHP String to Int example, we convert a string to a number using the intval() function. Below you can see more PHP string to int conversion examples with detailed descriptions of each method. Click Execute to run the PHP String to Int Example online and see the result.
How do I convert a string to a number in PHP? Execute
<?php
$string = "23";

echo intval($string);
?>
Updated: Viewed: 551 times

How to convert string to number using type casting in PHP?

In PHP, we can change the type of a variable using the cast syntax: (int/float/double)$variable. In most cases, this is not required since PHP does an implicit type conversion in most cases.

PHP String to Int Example
<?php
$str = "23";

echo (int)$str;
?>

#output: 23

How to convert string to integer in PHP?

To convert a string to an integer in PHP, you can use the intval() function:

PHP intval() Example
<?php
$str = "15";

echo intval($str);
?>

#output: 15

How to convert a string to a floating-point number in PHP?

To convert a string to a float in PHP, you can use the floatval() function:

PHP floatval() Example
<?php
$str = "15.5";

echo floatval($str);
?>

#output: 15.5

How to convert string to int by changing variable type in PHP?

To set or change the type of a variable in PHP, you can use the settype(variable, type) function. The function takes two parameters: the variable we want to change and the type of the variable we need (integer, float, string, array, object, null).

PHP settype() Example
<?php
$str = "791";

settype($str, 'integer');

echo $str
?>

#output: 791

How to format a number with a grouping of thousands in PHP?

To format a number with a grouping of thousands in PHP, you can use the number_format() function:

PHP number_format() Example
<?php
$str = "6500";
  
echo number_format($str);
?>

#output: 6,500

See also