Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String number to integer not working PHP

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

like image 400
Hassan Ila Avatar asked Aug 11 '26 20:08

Hassan Ila


2 Answers

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

like image 179
Mihai Matei Avatar answered Aug 13 '26 08:08

Mihai Matei


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']);
like image 39
Nirnae Avatar answered Aug 13 '26 09:08

Nirnae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!