Monty Shokeen
Read Time: 12 min
PHPLanguage FundamentalsProgramming Fundamentals
Working with numbers in PHP seems to be a trivial concept, but it can be quite confusing. It looks easy at first because PHP provides automatic type conversion. For example, you can assign an integer value to a variable, and the type of that variable will be an integer. On the next line, you can assign a string to the same variable, and the type will change to a string. Unfortunately, this automatic conversion can sometimes break your code.
There are a lot of types for numeric values as well. In this tutorial, you'll learn about integers and floats in PHP, as well as the functions which can be used to determine the type of numbers that we are dealing with and convert between them. You'll also learn how to convert integers and floats to and from numerical strings.
Different Types of Numbers in PHP
Integers
The most basic type of number in PHP is the integer. As you might already know, integers are numbers without any decimal part. For example, 2 is an integer, and so is 235298 or -235298. On the other hand, 2.0 and 3.58 are floats. We will discuss them in more detail later.
One important thing to remember is that it is not necessary that a number be of typeint
if it does not have a decimal part. For example,16 * 2.5
is exactly40
, but the type of this result will still be afloat
. When you are multiplying numbers, the final result will be of type float if at least one of the operands was a float. It doesn't matter if the final number has a decimal part or not.
Also, the maximum possible value an integer can have in PHP on your system can be obtained using the constantPHP_INT_MAX
. A value greater in magnitude than the value returned byPHP_INT_MAX
will be stored as a float even if it looks like an integer.
Generally, you would expect the result of the multiplication of two variables of typeint
to be of typeint
. However, it is not true in the case of an overflow. Multiplication of five or six different numbers can easily take you outside the bounds of theint
type. For example, the result of128*309*32*43*309
is a float on my system because it exceeds the value ofPHP_INT_MAX
, which is2147483647
.
You can use theis_int($value)
function to check if a number is of type integer. There are two aliases of this function, calledis_integer($value)
andis_long($value)
. Both of them will give the same result.
Floats
The next most common type of number that you will deal with is a float. Unlike integers, which were simply numbers without decimal points in most cases, a number of typefloat
can be represented in a variety of ways. The values3.14
,12.0
,5.87E+10
, and3.56E-5
are all floats.
PHP will automatically convert a number to thefloat
type whenever decimals or very large numbers are involved. Thefloat
type can commonly store numbers with magnitude approximately equal to1.7976931348623E+308
. However, this is platform dependent.
The value1.7976931348623E+308
may seem like a very large value—and it is!—but floats have a maximum precision of only about 14 digits. Any number with more digits than that will lose its precision. That means you can store a very large number, but you won't be able to keep the information about its exact value—in many cases, a float is only an approximation.
There are two functions which can be used to determine if the value you are dealing with is a float. These functions areis_float()
andis_double()
. Actually,is_double()
is just an alias ofis_float()
, so you can use any one of them and get the same result.
Infinity and NaN
There are two more kinds of numerical values that you might have to deal with when writing programs related to mathematics. These values are infinity andNaN
(not a number). Both these values require a little explanation because they are different from what you might expect.
Infinity in PHP is different from infinity in real life. In PHP, any numerical value above approximatelyPHP_FLOAT_MAX
on a platform is considered infinity. So1.8e308
will give youfloat(INF)
onvar_dump()
. You can check if a numerical value is finite or infinite using theis_finite()
andis_infinite()
functions.
Similarly,NaN
stands forNotaNumber, but it doesn't check if a value is numerical or not. The valueNaN
is used for the result of mathematical operations which are not possible in mathematics. For example,log(-1)
will beNaN
. Similarly,acos(5)
will also beNaN
. You can check if the value returned by a mathematical operation is not a number by using the functionis_nan()
.
Numerical Strings in PHP
Just as PHP dynamically changes the type of different numbers based on how their values are used or assigned, it can also infer the value of different numerical strings for you to convert them to numbers.
The functionis_numeric()
can help you determine if a string or variable is indeed numeric or not. This function will returntrue
for numbers written in octal, binary, or hexadecimal notation. It will also returntrue
if the numbers are written in exponential notation like+16.52e39
.
Starting from PHP 7.0.0, when you pass a string tois_numeric()
, it only returnstrue
if the string consists of an optional sign, some digits, an optional decimal, and an optional exponential part. This means that a numerical string written in hexadecimal or binary format will returnfalse
from PHP 7.0.0 onward.
PHP will implicitly cast any valid numerical string to a number when the need arises. The following examples should help you understand this process better.
1 | <?php |
2 | |
3 | $num = "3258712" + 12380; |
4 | // Output: int(3271092) |
5 | var_dump($num); |
6 | |
7 | $num = "3258712" + "12380"; |
8 | // Output: int(3271092) |
9 | var_dump($num); |
10 | |
11 | $num = 3258712 + "12380"; |
12 | // Output: int(3271092) |
13 | var_dump($num); |
14 | |
15 | $num = 3258712 * "12380"; |
16 | // Output: float(40342854560) |
17 | var_dump($num); |
18 | |
19 | $num = 3258712 / "12380"; |
20 | // Output: float(263.2239095315) |
21 | var_dump($num); |
22 | |
23 | $num = 3258712 / "8"; |
24 | // Output: int(407339) |
25 | var_dump($num); |
26 | |
27 | $num = "53.9e4" + 10; |
28 | // Output: float(539010) |
29 | var_dump($num); |
30 | |
31 | $num = "398.328" + 10; |
32 | // Output: float(408.328) |
33 | var_dump($num); |
34 | |
35 | $num = "398328" + 0xfedd24; |
36 | // Output: int(17101084) |
37 | var_dump($num); |
38 | |
39 | $num = 398328 + "0xfedd24"; |
40 | // Output: int(398328) |
41 | var_dump($num); |
42 | |
43 | ?> |
As you can see, all valid numerical strings were converted to their respective values before addition or other operations were performed. The type of$num
in the end depends on its final value.
In the last case, the hexadecimal string"0xfedd24"
is not converted to its decimal value because PHP 7 does not consider it to be a valid numerical string.
Casting Strings and Floats to Integers
Every now and then, you will need to cast one type of numerical value into another. PHP has a variety of functions and techniques to do so. Most of the time, the conversion will be implicit, and you won't have to worry about it. However, if you have to do the conversion explicitly, the techniques mentioned here will definitely help.
You can use(int)
or(integer)
to convert any value to an integer. In the case of floats, the values will always be rounded towards zero. Another way to cast strings and floats to integers is with the help of theintval()
function. Both(int)
andintval()
work in the same manner.
1 | <?php |
2 | |
3 | $float_a = 3598723.8258; |
4 | $int_cast = (int)$float_a; |
5 | // Output: 3598723 |
6 | echo $int_cast; |
7 | |
8 | $string_a = "98723.828"; |
9 | $int_cast = (int)$string_a; |
10 | // Output: 98723 |
11 | echo $int_cast; |
12 | |
13 | $string_b = "987233498349834828"; |
14 | $int_cast = (int)$string_b; |
15 | // Output: 2147483647 on a 32 Bit Machine |
16 | echo $int_cast; |
17 | // Output: 987233498349834828 on a 64 Bit Machine |
18 | echo $int_cast; |
19 | |
20 | |
21 | |
22 | $float_b = 21474836473492789; |
23 | $int_cast = (int)$float_b; |
24 | // Output: -6507212 |
25 | echo $int_cast; |
26 | ?> |
You should note that casting overflowing strings to integers will set the final value to the maximum permissible integer value. However, casting a float whose value is more than the maximum permissible integer value will result in the value oscillating between-2147483648
and2147483647
!
In certain situations, you might need to deal with very large numbers without losing any precision. For example, it is impossible to get an accurate result of the multiplication of987233498349834828
and3487197512
using the*
operator. It will give you3.4426781992086E+27
after float conversion. Calculating the actual answer, which is3442678199208600117812547936
, will require the use of libraries likeBCMath. BCMath works by storing numbers as strings and doing arithmetic operations on them manually. Just remember that if you use BCMath, you will be dealing with strings instead of integers and floats.
Certain libraries will want you to only pass numbers of typeint
to their methods, but you might unknowingly supply them a float value. This might happen because the value seems like an int because it doesn't have a decimal part. This would almost certainly result in an error if the library uses a function likeis_int()
to check if the passed number is of integer type. In such cases, it is always wise to first cast that number to int using either(int)
orintval()
and then pass it to any functions or methods of the library.
One example of when such a situation could come up would be when you are dealing with mathematical functions likefloor()
,ceil()
, etc.floor()
andceil()
will always return a float, even if you pass them an int!
1 | <?php |
2 | |
3 | $int_a = 15*12; |
4 | // Output: int(180) |
5 | var_dump($int_a); |
6 | |
7 | $num = floor($int_a); |
8 | // Output: float(180) |
9 | var_dump($num); |
10 | |
11 | ?> |
One problem with casting floats to integers is that you will lose the decimal part of the numbers. This may or may not be desirable. In such cases, you can use functions likefloor()
and only cast the number to int type if its actual value is equal to the value returned byfloor()
.
1 | <?php |
2 | |
3 | $number = 16*2.5; |
4 | |
5 | if(floor($number) == $number) { |
6 | $fraction->setNumerator((int)$number); |
7 | } else { |
8 | echo 'Did not set the numerator.'; |
9 | doSomethingElse(); |
10 | } |
11 | |
12 | ?> |
Let's say you have a library which allows you to do fractional arithmetic, and it throws exceptions when you pass a number to itssetNumerator()
method that is not of type int. A variety of operations might turn a number into type float even if it is still an integer within the minimum and maximum bounds of type int. Using something like the code above will help you deal with such cases easily.
Tips for Working With Numbers in PHP
Numbers themselves can be infinitely large, but our computers have limited computer memory. This can lead to problems when working with numbers in a programming language.
Problems With Fixed-Size Integers
The largest number you can store as a standard integer on a 64-bit machine is 9223372036854775807. Any calculations with a result greater than that cannot be done with simple integers and require other solutions. This means that you should not use regular integers when there is a chance that the result might go above these limits. One option for larger numbers is to use floating-point numbers. However, they have their own drawbacks!
Problems With Floating-Point Numbers
Floating-point numbers are very common for everyday calculations. However, anything that you do with numbers which relies on comparing them for equality can result in problems. This is because floating-point numbers have limited precision, so comparisons between them aren't always perfect. Not only that, but computers are binary systems, and our number systems are decimal. The conversion between them is not always accurate. For example, 0.1 cannot be accurately represented in binary—similar to how 1/3 cannot be exactly represented in a fixed number of decimal digits. There is always some loss of precision.
For applications like graphics rendering or games, this loss of precision is not a problem. However, for banking or eCommerce applications, it could create major issues. One way to avoid this error is to convert the numbers you are working with into integers! For example, anything that costs $12.01 can be stored with integers internally as 1201 cents. Always consider using regular integers instead of floating points when precision is necessary.
Unlimited Precision Numbers
The best way to get around the limitations mentioned in the above two points is to store numbers as strings. An arbitrary precision library like BCMathin PHP can help you with this. It comes with many useful functions to make it easier for you to add, subtract, divide and multiply very large numbers without losing precision.
1 | <?php |
2 | |
3 | // Output: 3072022.352153 |
4 | echo pow(145.37, 3); |
5 | |
6 | // Output: 3072022.352153 |
7 | echo bcpow('145.37', '3', 6); |
8 | |
9 | // Output: 3072022.35215300000000000000 |
10 | echo bcpow('145.37', '3', 20); |
11 | |
12 | // Output: 7.485894688036E+64 |
13 | echo pow(145.37, 30); |
14 | |
15 | // Output: 74858946880359568408424850947105278367228015491111279108371943756.809526 |
16 | echo bcpow('145.37', '30', 6); |
17 | |
18 | // Output: 74858946880359568408424850947105278367228015491111279108371943756.809526310877954976795991720196399964284058833429514016256049 |
19 | echo bcpow('145.37', '30', 60); |
20 | ?> |
As you can see, thebcpow()
function can set the precision to an arbitrary value defined by the third parameter.
Of course, this functionality comes at a cost—using BCMath is significantly slower than the built-in number types in PHP. It's best to use the built-in numeric types unless you need the extra precision and range.
Final Thoughts
This tutorial has covered different ways in which PHP stores numbers and how you can determine if a number is of a particular type. For example, you can use functions like is_int()
andis_float()
to determine the type of a number and proceed accordingly.
As you saw in the tutorial, PHP supports automatic type conversion. This means that sometimes smaller integers like5
or476
could have been stored as floats without you realizing it.Using these numbers in functions which only acceptint
values might result in exceptions or errors. We learned that a simple solution to this problem is to explicitly cast such numbers toint
if they don't have a decimal part and their values don't change upon casting.
After reading this tutorial, you should be able to determine the type of a number or the final type of a result after using a variety of operations with predefined functions and also explicitly cast them to a specific type after doing some checks.
As always, if you have any questions or additional tips, you are welcome to comment.
Learn PHP With a Free Online Course
If you want to learn PHP, check out ourfree online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
- PHP FundamentalsJeremy McPeak29 Oct 2021
Monty Shokeen
Freelancer, Instructor
I am a full-stack developer who also loves to write tutorials. After trying out a bunch of things till my second year of college, I decided to work on my web development skills. Starting with just HTML and CSS, I kept moving forward and gained experience in PHP, JavaScript, and Python.I usually spend my free time either working on some side projects or traveling around.
FAQs
How do you check if a number is integer or float in PHP? ›
The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.
How to check if a value is string or integer in PHP? ›The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.
How to force string to integer in PHP? ›Converting String to Int 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.
How can I get integer value in PHP? ›The intval() function returns the integer value of a variable.
How do you check if a string is a float or an int? ›Use isinstance() to check if a number is an int or float
Call isinstance(object, classinfo) with the number as object and classinfo as either int or float to return True if object is an instance of classinfo and False otherwise.
The isdigit() method is an attribute of the string object to determine whether the string is a digit or not. This is the most known method to check if a string is an integer. This method doesn't take any parameter, instead, it returns True if the string is a number (integer) and False if it's not.
How do you know if a value is string or number? ›- Integer. parseInt(String)
- Float. parseFloat(String)
- Double. parseDouble(String)
- Long. parseLong(String)
- new BigInteger(String)
To check if the string contains numbers only, in the try block, we use Double 's parseDouble() method to convert the string to a Double . If it throws an error (i.e. NumberFormatException error), it means the string isn't a number and numeric is set to false . Else, it's a number.
How do you check if a value is a string? ›To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.
Can string values be converted to integer values? ›Use Integer.parseInt() to Convert a String to an Integer
This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
How to convert string value to int? ›
- Java string to int using Integer.parseInt(String) parseInt is a static method of the Integer class that returns an integer object representing the specified String parameter. Syntax: ...
- Convert using Integer.valueOf(String) Integer. valueOf(String s) is a Java method of Integer class.
We can convert int to String in java using String.valueOf() and Integer.toString() methods. Alternatively, we can use String.format() method, string concatenation operator etc.
What is the limitation of a PHP integer value? ›PHP Integers
An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.
Use preg_match_all() method with /[0-9]+/ to extract numbers from String in PHP. Here, output is array of matches, which can then be used to extract the numbers from the string.
How to use number format in PHP? ›Basic number formatting
In its most basic form, number_format() accepts a number to format, and returns a string containing the formatted number, rounded to the nearest whole number, with commas between each group of thousands: $myNumber = 1234567.89; // Displays "1,234,568" echo number_format( $myNumber );
Most commonly used data types in Java are int (integer), char (character), float (number having decimal), double (number having decimal), String (collection of characters) and boolean (true or false).
How do I check if a string is valid float? ›Use isdigit() Function and replace() Function
We can check whether the entered string is float or not by combining the isdigit() and replace() functions. The integer value is eliminated first, then the string is merged to create a numeral, and the result is evaluated.
For converting strings to floating-point values, we can use Float. parseFloat() if we need a float primitive or Float. valueOf() if we prefer a Float object.
How do you check if a value is an integer or a string in SQL? ›To check if the given value is a string or not ,we use the cast() function. If the value is not numeric then it returns 0, otherwise it will return the numeric value. In this way, we can check whether the value is an integer or not.
How do you identify an integer? ›An integer (pronounced IN-tuh-jer) is a whole number (not a fractional number) that can be positive, negative, or zero. Examples of integers are: -5, 1, 5, 8, 97, and 3,043. Examples of numbers that are not integers are: -1.43, 1 3/4, 3.14, .
What is the difference between a number and a string? ›
Integer is a numeric value, while String is a character value represented in quotes.
What is the difference between value and string? ›The important thing to note is that String(val) creates a new object whereas value as String simply refers to value (and tests for compatibility to String). It is not true that the Type(variable) syntax necessarily creates a new object. It is not the same as a constructor (though it looks like it).
How do you check if it is a string type? ›Using type() method
The second approach is by using the inbuilt method type(). This method takes an input and returns the type of the given input. We will return True if the type is string otherwise return False.
The isdigit() method returns True if all characters in a string are digits. If not, it returns False .
How do I check if a string contains letters and numbers? ›To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.
How do you check if a variable is a string in PHP? ›The is_string() function checks whether a variable is of type string or not. This function returns true (1) if the variable is of type string, otherwise it returns false/nothing.
What is an example of a string value? ›A string value is just a sequence of characters, like "abc" . A string value is always enclosed in quotes. All types of characters are allowed (even digits, as in "abc123" ).
Which function converts a string to integer or float value? ›We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number.
Can you add ints and strings? ›To concatenate a String and some integer values, you need to use the + operator. Let's say the following is the string. String str = "Demo Text"; Now, we will concatenate integer values.
Can you assign a number or a string to a variable? ›Variables and Type
The act of assignment to a variable allocates the name and space for the variable to contain a value. We saw that we can assign a variable a numeric value as well as a string (text) value.
What is the size limit for strings in PHP? ›
A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.
What is the limit of integer data type? ›The INTEGER data type stores whole numbers that range from -2,147,483,647 to 2,147,483,647 for 9 or 10 digits of precision.
Is there a limit to string length PHP? ›Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.
How to separate string and integer in PHP? ›...
- Using preg_match_all() Function.
- Using filter_var() Function.
- Using preg_replace() function.
This is called variable variables. In your loop, the code will set the variable who's name is $key to the value $val . The loop could be replaced with extract() . Follow this answer to receive notifications.
How do I remove all non numeric characters from a string in PHP? ›You can use the preg_replace function in PHP to remove all non-numeric characters from a string. The regular expression to match non-numeric characters is /[^0-9]/ , and you can use an empty string as the replacement.
What does '@ number_format do? ›The number_format() function formats a number with grouped thousands. Note: This function supports one, two, or four parameters (not three).
How to format a float number in PHP? ›PHP: number_format() function
The number_format() function is used to format a number (Floating number) with grouped thousands. The input number. Refer to the number of decimal points. Refers the separator of decimal points.
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
What is the difference between integer and float in PHP? ›An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.
How do you check and verify the type of data types in PHP? ›
You can use gettype(); to check datatype of variable in php.
How to check if a number is not a decimal in PHP? ›In PHP, you can use the is_float() function to check if a variable is a decimal number. Another way is using the fmod() function, which returns the remainder of dividing two numbers. If the remainder is not zero, it means that the number is decimal.
How do you recognize a variable in PHP? ›A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Should I use integer or float? ›Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.
Why is it necessary to treat integer and floating point numbers so differently? ›It is important to take note that integers and floating-point numbers are treated differently in computers. They have different representation and are processed differently (e.g., floating-point numbers are processed in a so-called floating-point processor).
Is it better to use float or int? ›A "float" is a floating-point number - that is, a number and part of a number. If you need to store/represent a value that can be between integers, you could use a float. Floats use more RAM than integers, and there is a limit to the precision they can represent. Don't use a float unless you have a need.
What are the 4 main data types in PHP? ›String. Integer. Float (floating point numbers - also called double) Boolean.
How to check data type of value in PHP? ›The gettype() function is an inbuilt function in PHP which is used to get the type of a variable. It is used to check the type of existing variable. Parameter: This function accepts a single parameter $var. It is the name of variable which is needed to be checked for type of variable.
How do I check if a string is valid in PHP? ›The is_string() function checks whether a variable is of type string or not. This function returns true (1) if the variable is of type string, otherwise it returns false/nothing.
How do you check if a string contains decimals? ›Using the isdigit() function
One way to achieve this is using the inbuilt string function isdigit(). The function takes the input as a string and returns true if all the characters present in the string are digits otherwise it returns false.
How do you check if a string is decimal or not? ›
The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.
How do you check the answer to a decimal? ›Explanation : To check the answer to a decimal multiplication problem, you can divide the product with one of the decimal numbers. If the answer is equal to the other number, then your answer is correct.
What is @$ variable in PHP? ›The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc.
How to declare integer variable in PHP? ›PHP doesn't by default make a variable integer or string, if you want to set default value, then simply write $myvariable = 0; and this will assign and make variable an integer type.
How do you check if a variable has any value? ›Answer: Use the typeof operator
If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.