PHP is a weakly typed language. This means that when initializing a variable in PHP, one doesn’t need to declare the variable type. PHP implicitly declares a data type for your variable. This can save you from prospective type errors in your code.
When working with programming languages, it is quite common to want to do things with numbers that are represented as strings. For example, performing arithmetic operations, responding to a client request, feeding the data to a database etc. Even though PHP helps with implicit type conversion in some cases, it is important to know about appropriate methods that can facilitate type conversion.
In this guide, we’ll explore the different ways to convert a string to a number in PHP.
Use the links below to skip ahead in the tutorial:
- Background: Types of PHP Numbers
- Convert a String to a Number Using Type Casting
- Convert a String to a Number Using intval()
- Convert a String to a Number Using Mathematical Operations
- Formatting Number Strings Using number_format()
- Test it for yourself
Background: Types of PHP Numbers
Numbers in PHP can take four forms:
- Integers
- Floats
- Infinity
- NaN
Here, integers and floats represent the more commonly used number formats in programming languages, and in everyday life. On the other hand, Infinity and NaN are not as well-defined and are more likely to be encountered in edge-cases. Let us look at these in some more depth.
Integers
Integers are the numbers that do not contain a decimal component. They constitute the set Z={..,-3,-2,-1,0,1,2,3..}. If you initialise a variable in PHP as a number that does not have a decimal component, it takes the integer data type (unless it has a value greater than PHP_INT_MAX).
You can verify if a variable is an integer by using the is_int() function, as shown below.
<?php
$x = 42; # integer
$y = "42" # string
var_dump(is_int($x)); # Output: bool(true)
var_dump(is_int($y)); # Output: bool(false)
?>
PHP Floats
Float numbers are those that contain a decimal component or are represented in an exponential form. These numbers encompass a higher range of numbers, take up more bytes per number, and are precise up to 14 decimal places. Here are some examples of float numbers –
0.08, 2.39, 132.5, 2.0, 1.3e5, 2e10, etc.
It is important to note that arithmetic operations performed between a float number and an integer always return a float number (even if the returned number does not need a decimal part). For example –
<?php
$my_float = 8.0;
$my_int = 2;
var_dump($my_float - $my_int); # Output: float(6)
var_dump($my_float + $my_int); # Output: float(10)
var_dump($my_float * $my_int); # Output: float(16)
var_dump($my_float / $my_int); # Output: float(4)
?>
You can verify if a variable is a float number by using the is_float() function, as shown below.
<?php
$x = 4.2; # float
$y = 42; # integer
var_dump(is_float($x)); # Output: bool(true)
var_dump(is_float($y)); # Output: bool(false)
?>
PHP INF (Infinity)
‘INF’ in PHP stands for infinity. In programming languages, it is commonly used to represent any number that is greater than the maximum possible float value (which is platform-dependent in PHP).
INF is usually encountered any time you happen to divide an integer or float number by zero.
INF can also be in the negative form, which can be encountered when you perform an operation like log(0).
You can verify if a variable is INF by using the is_infinite() or is_finite() function as shown below.
<?php
$x = 42;
$y = $x/0;
echo $y; # Output: INF
echo log(0); # Output: -INF
var_dump(is_infinite($y)); # Output: bool(true)
var_dump(is_finite($y)); # Output: bool(false)
?>
PHP NaN
NaN stands for ‘Not a Number’. It represents outputs of mathematical operations that can not be defined. For example, the arc cosine of x, i.e. acos(x) is undefined for x > 1 and x < 1.
You can verify if a variable is NaN by using the is_nan() function as shown below.
<?php
$x = acos(1.01); # acos(x) is undefined for x>1 and x<1
echo $x; # Output: NaN
var_dump(is_nan($x)); # Output: bool(true)
?>
Convert a String to a Number Using Type Casting
To convert a PHP string to a number, we can perform type casting using (int) or (float) keywords as shown below.
<?php
$my_str = "123"; # string
var_dump($my_str); # Output: string(3) "123"
$my_int = (int)$my_str; # Casting to integer
var_dump($my_int); # Output: int(123)
?>
Similarly, we can also cast PHP strings to float values using (float).
<?php
$my_str = "1.23"; # string
var_dump($my_str); # Output: string(4) "1.23"
$my_int = (float)$my_str; # Casting to float
var_dump($my_int); # Output: float(1.23)
?>
Using (int), we can also convert PHP strings that represent float numbers (eg. “1.78”, “18.19”) directly to integers. This operation floors the float number (eg. “18.19”) down to it’s nearest integer (18). For example –
<?php
$my_str = "12.3"; # string
var_dump($my_str); # Output: string(4) "12.3"
$my_int = (int)$my_str; # Casting to integer
var_dump($my_int); # Output: int(12)
?>
Convert a String to a Number Using intval()
To convert a PHP string to a number, we can also use the intval() or floatval() function. Below are a few examples of intval()’s usage.
<?php
var_dump(intval("12.0")); # Output: int(12)
var_dump(intval("12")); # Output: int(12)
var_dump(intval("12.3")); # Output: int(12)
var_dump(intval("12.9")); # Output: int(12)
var_dump(intval("1.29e2")); # Output: int(129)
var_dump(intval("1e2")); # Output: int(100)
?>
intval() can also be used to convert strings from hexadecimal (base 16) and octal (base 8) number systems to integers of decimal representations (base 10). The intval() function can also use a second parameter that specifies the base for conversion. The default base value is 10 (for decimal representations).
<?php
echo intval('0x1A', 16); # Hexadecimal base; Output: 26
echo intval('42', 8); # Octal base; Output: 34
?>
Apart from string to integer conversion, intval() can also be used to convert strings of float numbers to integers.
Similarly, we can use floatval() to convert to float numbers.
<?php
var_dump(floatval("12")); # Output: float(12)
var_dump(floatval(12)); # Output: float(12)
var_dump(floatval("12.3")); # Output: float(12.3)
var_dump(floatval("12.9")); # Output: float(12.9)
var_dump(floatval("1.29e2")); # Output: float(129)
var_dump(floatval("1e2")); # Output: float(129)
?>
Convert a String to a Number Implicitly using Mathematical Operations
If you have a number that is initialized as a string in your code, PHP allows you to perform arithmetic operations directly on that string variable. This means that PHP implicitly performs the type conversion so that your code doesn’t raise an error. These are seemingly some of the advantages of weakly (or loosely) typed languages like PHP.
Let’s see how we can leverage this implicit type conversion to our advantage.
<?php
$x = "39";
$y = $x + 0; # adding zero so that our variable doesn't change
var_dump($y); # Output: int(39)
?>
As can be seen above, even though we started with a string variable, a trivial arithmetic operation has implicitly converted it to an integer.
Agreed, this is not the most elegant approach to convert a string to a number, but in many cases, it can still save you from an explicit type conversion.
Formatting Number Strings Using number_format()
Before we close, I’d like to shed some light on how we can format number strings (numbers stored as strings) to improve presentation.
Some posts on the internet incorrectly claim that number_format() function can be used to convert a string to a number. This is not true.
The number_format() function can be used to format numbers that are stored in the form of strings – by adding commas to separate between thousands and/or specifying the number of decimal places. The function always returns a formatted string (not a number variable) and can be used as shown below –
number_format(string_number, n_decimal_places , decimal_point_symbol, separator_symbol)
All arguments here, except the first one (string_number) are optional.
Let’s look at a few examples.
<?php
# adding only commas between thousands
var_dump(number_format("4200")); # Output: string(5) "4,200"
var_dump(number_format("42000000")); # Output: string(10) "42,000,000"
# formatting upto two decimal places
var_dump(number_format("4200000",2)); # Output: string(12) "4,200,000.00"
var_dump(number_format("4200.515",2)); # Output: string(8) "4,200.52"
?>
Test it for Yourself
In this post, we looked at different types of numbers in PHP – integers, float numbers, INF (infinity), and NaN. We also looked at how we can convert PHP strings into numbers using various methods – by typecasting, using intval() and floatval() methods, and also by implicit conversion using mathematical operations. We also looked at how we can use the number_format() function to format number strings to improve presentation.
Now that you know about numbers in PHP, about how to convert strings to numbers and about number string formatting, go ahead and try it out. Choose whichever conversion method suits you best and implement what you learned in this post.
Stay healthy, stay safe! Happy coding!