LAST UPDATED: AUGUST 4, 2021
How to Convert a String to a Number in PHP?
Answer: Using Type Casting
We can convert the strings to a number by using typecasting. As we know PHP does not support explicit type conversion while declaring a variable. But there is a various method offered by PHP which enables us to convert the string to a number.
Example: Using typecasting
With the help of typecasting, we can convert any string into numbers (integer, float, double) without using any built-in function. In the given example, we have performed type casting and converted the string into numbers.
<!DOCTYPE html>
<html>
<head>
<title>PHP Type Casting</title>
</head>
<body>
<?php
$num = "3.14";
// Cast to integer
$int = (int)$num;
echo gettype($int), "<br>";
echo $int, "<br>";
</body>
</html>
Output
integer
3
Example: Using intval() and floatval() function
The intval()
and floatval()
function is used to convert the string into the integer and the float data type. In the given example, we have used the intval()
function that converts the string into the integer type, and the floatval()
value to convert the string into the float type.
<!DOCTYPE html>
<html>
<head>
<title>PHP date and time</title>
</head>
<body>
<?php
$num = "123.314";
echo intval($num), "<br>";
echo floatval($num);
?>
</body>
</html>
Output
123
123.314
Conclusion
In this lesson, we have explained how to convert the string into numbers. There are several methods in PHP to convert a string into numbers. In this lesson we have covered two methods, first one is typecasting and in the second method we have used the intval()
and floatval()
function.