22

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!

Maciej Jankowski
  • 2,794
  • 3
  • 26
  • 33
  • 8
    `(float) "your string"` – PeeHaa Jun 02 '14 at 19:52
  • 1
    Are you on a 32-bit platform? You'll need to use `float` instead of `int`, since that number is too large for a 32-bit signed integer. – Barmar Jun 02 '14 at 19:53
  • The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. http://www.php.net/manual/en/function.intval.php – Vincent Decaux Jun 02 '14 at 19:53
  • 2147483647 is the maximum integer value on 32bit systems. – barell Jun 02 '14 at 19:53
  • Related `var_dump(PHP_INT_MAX);` – PeeHaa Jun 02 '14 at 19:53

1 Answers1

19

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.

Jon
  • 428,835
  • 81
  • 738
  • 806