PASSWORD RESET

Your destination for complete Tech news

PHP

How to convert a string to a number in PHP?

310 0
< 1 min read

There are several ways to convert a string to a number in PHP. Here are some options:

1. Use the intval function to convert a string to an integer:

$str = '123';
$num = intval($str);  // $num is now 123

2. Use the floatval function to convert a string to a float:

$str = '123.45';
$num = floatval($str);  // $num is now 123.45

3. Use the settype function to set the type of a variable to “integer” or “float”:

$str = '123';
settype($str, 'integer');  // $str is now 123

$str = '123.45';
settype($str, 'float');  // $str is now 123.45

4. Use the (int) or (float) type casts to convert a string to an integer or float, respectively:

$str = '123';
$num = (int) $str;  // $num is now 123

$str = '123.45';
$num = (float) $str;  // $num is now 123.45

Which method you choose will depend on your specific needs and the format of the string you are trying to convert.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.