Page 1 of 1

Need help with unserialize

Posted: Mon Aug 13, 2007 10:06 am
by aye
Hi,
It seems storing integers over the unsigned limits results in errors when unserializing an 'array string'. I.e. this code:

Code: Select all

<?php
$test = unserialize('a:1:{s:5:"value";i:2147483648;}');
print_r($test);
?>
Would result in the browser outputting a faulty value for the key "value", while this code

Code: Select all

<?php
$test = unserialize('a:1:{s:5:"value";i:2147483647;}');
print_r($test);
?>
will output the correct value.
So I figured I could add something like this for the bigger ints:

Code: Select all

$diff = 2147483648 + $test["value"];
$test["value"] = $diff + 2147483648;
but that won't work very well in the long run either, as only signed integers would work then..

So..: how should i go about unserializing an array with big integers? is there some easier way to store arrays with big ints in a database?

thanks, aye

Posted: Mon Aug 13, 2007 10:10 am
by s.dot
Couldn't you just store them as strings? Then typecast when you unserialize?

Code: Select all

$array = array('number' => '2839824984492');
$array = serialize($array);
print_r($array);

$array = unserialize($array);
$number = (int) $array['number']
var_dump($number);
EDIT| I tested it.

Code: Select all

C:\Users\HP_Administrator>php -r "$array = array('number' => '8239824902840923')
;  $array = serialize($array); print_r($array);  $array = unserialize($array);
$number = (int) $array['number']; var_dump($number);"

a:1:{s:6:"number";s:16:"8239824902840923";}
int(2147483647)
It gets stored fine, but when typecasting it to (int), it takes the int down. You might be able to stick with using strings instead of integers, since php is not type sensitive.

Posted: Mon Aug 13, 2007 10:52 am
by feyd
Yes, you're hitting the limits of 32 bit signed integers. Use arbitrary integers if you need large integer support. http://php.net/ref.bc

Posted: Mon Aug 13, 2007 1:44 pm
by aye
thanks for your help guys. i guess i will be fine with using strings instead then :wink: