1

So I have this simple code:

$var = abs(crc32('string - 8 characters')).rand(100,999);
var_dump($var);
echo '<br>';
var_dump((int)$var);
echo '<br>';
var_dump(intval($var));

And the result:

string(13) "2047654753402"
int(2147483647)
int(2147483647) 

Why the integer value is 2147483647? I expected it to be 2047654753402. I just want to convert the string to integer without changing the value.

3
  • 3
    Considering that your integer is a signed 32-bit integer..... what do you expect to happen when your string value is outside of that range? There's even a whole page of the PHP Documents that explains what happens when you have an integer overflow - php.net/manual/en/language.types.integer.php Commented May 30, 2016 at 17:19
  • 1
    If you need to work with integers that size, switch to 64-bit PHP Commented May 30, 2016 at 17:21
  • 1
    Why the integer value is 2147483647? Because 2147483647 is the maximum value that can be stored in a 32-bit signed integer Commented May 30, 2016 at 17:30

1 Answer 1

1

You can not convert large string number to integer because interger has limitation -2147483647 to 2147483647. So If you want to convert number string to integer which has out of range of integer length, you can use double.

$var = abs(crc32('string - 8 characters')).rand(100,999);
var_dump($var);
echo '<br>';
var_dump((double)$var)
Sign up to request clarification or add additional context in comments.

5 Comments

If you're recommending this as a solution, it might be worth noting that it will likely result in some loss of precision
What's wrong with this solution? I just want to be able to put this long number into database in BIGINT column. This (double) returns a float number. Will it be correct to put it into BIGINT?
What's wrong with this solution? What's wrong is potential lack of precision..... try running $var = abs(crc32('string - 8 characters')).rand(100,999); var_dump($var); $var2 = (double)$var; var_dump($var2); $var3 = (string)$var2; var_dump($var3); and see if $var3 is the same as $var
Well, I've checked on 3 different servers and $var3 returns exactly the same result as $var.
@Qrzysio - That's not guaranteed when the value is larger than PHP_INT_MAX.... it can also be affected by the precision setting in your php.ini file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.