PHP intval | How to Covert PHP string to int with Example?
Summary: in this article, you will learn How to Covert PHP string to int(integer) with Example? In this guide, I will show you four different methods to accomplish this, such as-
- 1st method: using number_format() Function
- 2nd method: using intval() and floatval() Function
- 3rd method: using type casting
- 4th method: By adding 0 or by performing mathematical operations.
Answer: To Covert PHP string to int
Strings in PHP can be converted to numbers (float/int/double) terribly simple. In most use cases, it won’t be needed since PHP does implicit type conversion. There are many methods to convert PHP string to integer. but here, I will discuss four methods as given below:
I-method: Using number_format() Function
Using PHP number_format() Function. The number_format() function in PHP is used to convert the string into a number. furthermore, it returns the formatted number on success otherwise it will give E_WARNING on failure.
Example:
1,500.23
1,000
999.51
II-method: Using intval() and floatval() Function
To convert the string into its corresponding integer(int) and float values respectively used PHP intval() and floatval() Function. let’s see the example.
Example:
1500.225
999
999.514
III-method: Using type casting
Typecasting can directly convert a string into a float, double, or integer primitive type. This is the most effective and best way to convert a string into a number without any function.
100000.225
100000.225
As we all know that PHP doesn’t need or support explicit type definition in variable declaration. furthermore, you can force a variable to be evaluated as a certain type using the typecasting method.
Let’s see another example to understand how this works:
double25.86
You can use (int) or (integer) to cast a variable to an integer, use (float), (double), or (real) to cast a variable to float. Similarly, you’ll be able to use the (string) to cast a variable to string, and so on.
The gettype() function in PHP returns "double" in the case of a float for historical reasons.
Alternatively, you can also use the PHP intval() function to get the integer value of a variable.
IV-method: By adding 0 or by performing mathematical operations
By adding 0 or by performing mathematical operations. Therefore, the string number can also be converted into an integer(int) or float by adding 0 with the string. furthermore, in PHP, performing mathematical operations, the string is converted to an integer(int) or float implicitly.
9999.513
9999.613
PHP string to int conclusion
In this article, you have learned the conversion of PHP string to an integer using four different methods for example. I hope you will enjoy it!. if have any query then contact on info@tutorialscan.com I will try to resolve the problem.