String number to integer not working PHP

653 Views Asked by At

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()

2

There are 2 best solutions below

5
Mihai Matei On BEST ANSWER

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

0
Nirnae On

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']);