Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of converting string to long int in PHP

Tags:

I tried (int) "4209531264" and intval("4209531264") but sadly all I get is 2147483647 (I realize this is because of 32 bit architecture or some php dependencies or something).

I came up with "4209531264" + 0 which returns the correct result but it is surprising to see it working since it is beyond maxint.

but the real question: is this the "right way" of converting string to long?

edit:

(float) that is.

thanks for the comments! eye opening!

like image 686
Maciej Jankowski Avatar asked Jun 02 '14 19:06

Maciej Jankowski


People also ask

How do I convert a string to an integer in PHP?

The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly. echo $num + 0.1; ?>

Which function converts string into long int value?

In the C Programming Language, the strtol function converts a string to a long integer. The strtol function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

What is use of Intval function in PHP?

The intval() function is an inbuilt function in PHP which returns the integer value of a variable. Parameters: This function accepts two parameters out of which one is mandatory while the other one is optional.


1 Answers

As long as you are not very particular about what exactly kind of value you end up with, "number" + 0 is probably the best way of converting your input because it converts to the "natural" numeric data type.

The result will be an integer if the input has no decimal part and fits (see PHP_INT_MAX) or a float if it does not.

like image 161
Jon Avatar answered Oct 19 '22 14:10

Jon