Working With Tweet IDs in PHP

I was playing with the Twitter search API today when I came across a strange problem. I was storing the unique ID of a tweet in the database as a string, and after bringing it out was trying to convert it back to an integer. However, the following code:

// this was the string of the tweet ID
echo "Tweet ID: {$stringID}<br />";
// turning it into an integer
$intID= (int) $stringID;
echo "Tweet ID: {$intID} <br />";

produced this erroneous output:

Tweet ID: 3296646743
Tweet ID: 2147483647

I finally realized that tweet IDs are too large to fit inside a simple integer data type. Doh!

The maximum value of an integer in PHP is 2147483647. It simply threw away all the high order bits. Haha.

To fix this issue, all you need to do is use a double data type instead.

// this was the string of the tweet ID
echo "Tweet ID: {$stringID}<br />";
// turning it into an integer
$intID= (double) $stringID;
echo "Tweet ID: {$intID} <br />";