1

I would like to convert a 17 digit unique ID retrieved as a string from my MYSQL database to a number. I use the int to do so. However I get a zero at the end:

$num = 96435171263250434;
(int)$num --> 96435171263250430

I've checked I am running a 64 bit system. I get the following:

php -r 'echo PHP_INT_MAX;'
9223372036854775807

How do I fix this issue???

1
  • 1
    What I'm going to say here shouldn't be any different I think, but have you tried using the intval() function? It returns the integer value of a string. Commented Jun 5, 2016 at 5:26

1 Answer 1

1

You cannot exceed PHP_INT_MAX

$num = "96435171263250434";

$x = (float) $num; // This should hold it but it's a float

$maxIntMult = 0;

$maxIntMult = intval($x / PHP_INT_MAX); 

$remainder = $x - $maxIntMult * PHP_INT_MAX;


echo PHP_INT_MAX . " x "  .$maxIntMult. " + " . $remainder; // function of two integer if you can't work with floats and you can make something of this

You can try to make use of the fact that ids don't have negative values, effectively doubling your range.

$num = PHP_INT_MAX + 50;

$x = (float) $num;

$intX = $num - PHP_INT_MAX;

echo $intX; // Shows 50 with the '0' being -PHP_INT_MAX



function getIdWithNonZeroOffset($stringId)
{
   $x = (float) $stringId;

  $intX = $x - PHP_INT_MAX;

   return $intX; 
}

function getStringFromNonZeroOfssetId($id)
{
   return (string) ($id + PHP_INT_MAX);
}

echo getIdWithNonZeroOffset((string)(PHP_INT_MAX + 200)); // Gives 200 (store this in int column)

echo getStringFromNonZeroOfssetId(200); // Gives "2147483847" (my max int is "2147483647")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I am assuming there is not easy solution. As such I've decided to keep it as a string and work it like that. Appreciate the answer above tbough.

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.