Need help with unserialize

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aye
Forum Commoner
Posts: 25
Joined: Wed Apr 11, 2007 9:02 am

Need help with unserialize

Post 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
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post 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.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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
aye
Forum Commoner
Posts: 25
Joined: Wed Apr 11, 2007 9:02 am

Post by aye »

thanks for your help guys. i guess i will be fine with using strings instead then :wink:
Post Reply