Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert a string into number in PHP?
PHP provides several methods to convert strings into numbers. The most common approaches are type casting, built-in functions like intval() and floatval(), and adding zero to the string.
Using Type Casting
Type casting is the most direct method to convert a string to a specific numeric type ?
<?php
$str = "150";
$num = (int)$str;
echo "Original String: $str<br>";
echo "Converted Integer: $num";
?>
Original String: 150 Converted Integer: 150
Using floatval() Function
For decimal numbers, use floatval() to convert strings to floating-point numbers ?
<?php
$str = "100.56";
echo "String: $str<br>";
$num = floatval($str);
echo "Number (Float): $num";
?>
String: 100.56 Number (Float): 100.56
Using intval() Function
The intval() function extracts integer values from strings, including those with mixed content ?
<?php
$str1 = "123abc";
$str2 = "456.78";
echo "String 1: $str1 ? " . intval($str1) . "<br>";
echo "String 2: $str2 ? " . intval($str2);
?>
String 1: 123abc ? 123 String 2: 456.78 ? 456
Comparison
| Method | Output Type | Handles Decimals | Mixed Content |
|---|---|---|---|
(int) |
Integer | Truncates | Extracts leading digits |
intval() |
Integer | Truncates | Extracts leading digits |
floatval() |
Float | Yes | Extracts leading number |
Conclusion
Use type casting (int) or (float) for clean numeric strings, and intval() or floatval() functions when dealing with mixed content or when you need more explicit conversion.
Advertisements
