3

I am trying to get a string number to an integer but it's not working as expected here is the code with the problem:

$usage['msisdn'] = "46720000000";
$usage['msisdn'] = (int)$usage['msisdn'];

echo $usage['msisdn'];

It echoes 2147483647 as integer but I want to get 46720000000 as integer.
What's wrong?

By the way I'm parsing the data using json_encode();


UPDATE: Nevermind I've got it to work with intval()

Cœur
  • 37,241
  • 25
  • 195
  • 267
Hassan Ila
  • 574
  • 1
  • 6
  • 20

2 Answers2

7

That's because the maximum value of int32 is 2,147,483,647. Your phone number exceeds this value.

You can find the maximum value of int on your server using:

echo PHP_INT_MAX;

I think that storing a phone number as integer is a bad practice and it may affect you later. Why? Because the phone number may start with:

  • IDD: 00 or +
  • NDD: 0

Also, you may want to format the phone number at some point, storing it as string making this part much easier.

Christmas bonus :) libphonenumber-for-php

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • How can I fix this then?? – Hassan Ila Dec 16 '15 at 08:56
  • 1
    The only way is to upgrade the server to a 64 bits OS and HW. I suggest you to keep to phone numbers as strings. In fact, the phone number is a string, because it may start with IDD `00`, `+` or NDD `0`, or the country code may start with `0` as well. Also, saving it as string may help if you want to format the phone number. – Mihai Matei Dec 16 '15 at 08:59
  • 1
    Edited my answer, just above, since you cannot modify the max_int value easily, you could try to use a conversion to float instead. – Nirnae Dec 16 '15 at 09:01
  • 1
    Thank you @MateiMihai I didn't know it's better to store tel. numbers as strings. Now I will just let it be a string :) – Hassan Ila Dec 16 '15 at 09:04
  • 1
    Thank you also for the Christmas bonus ;) @MateiMihai – Hassan Ila Dec 16 '15 at 09:10
4

Your code isn't working because the conversion string to int as a maximum value based on your system as quoted in the documentation :

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. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Source : http://php.net/manual/en/function.intval.php

Since you cannot modify the max_int value easily, you could try to use a conversion to float instead.

$usage['msisdn']  = floatval($usage['msisdn']);
Nirnae
  • 1,315
  • 11
  • 23