3

I got problem with this code:

if (!empty($_GET[ "lic" ])) $lic = $_GET[ "lic" ]; else $e = true;
echo ($lic % 11);

When I post 8911076856 it echoes 1, but it should be 0.

7
  • 4
    Might that be because 8911076856 is too high for an int, and overflowing? Commented Aug 22, 2012 at 14:03
  • I think that's not the problem as var_dump(8911076856 % 11); returns int(0). Call var_dump($lic) before echoing the modulo. Commented Aug 22, 2012 at 14:06
  • 1
    @Florent - that is the problem. It's a 32bit system and he's trying to handle value too large to fit 4 byte integer. You probably tested on 64 bit system. Commented Aug 22, 2012 at 14:08
  • @Florent: In that operation, the number 8911076856 is parsed as a float, but cast internally to an integer for the modulus. Try var_dump((int)8911076856); to see what it's actually using in the operation. Commented Aug 22, 2012 at 14:09
  • probably its 32b system, i dont know it exactly (Apache/2.2.15 (Debian) Server), but if it doesnt work, than is easy to find out Commented Aug 22, 2012 at 16:43

3 Answers 3

9

The value "8911076856" is probably above the maximum integer value of your system.

echo ((int)8911076856);

My result is 321142264 on my 32 Bit system.

Sign up to request clarification or add additional context in comments.

2 Comments

That's right, I got the right result (0) on a 64bits system
In this case, PHP automatically converts the number to a float. Apparently, the modulo operator does not work correctly on floats.
7

Use fmod:

echo fmod(8911076856, 11);

2 Comments

+1. Out of curiosity, is the benefit of fmod() over (float)$x % (float)$y just the precision of the result?
No, (float)$x % (float)$y does not give the correct result for values of $x above PHP_INT_MAX. E.g. (float)8911076856 % (float)10 gives 4 instead of 6. Apparently the modulo operator casts both arguments back to int.
2

This is most likely being caused because the number you're posting is higher than PHP_INT_MAX, which is 9223372036854775807 on most 64-bit systems AFAIK. If you're using a 32-bit system (which I expect you are), it's probably 2147483647.

2 Comments

On 32-bit machines, it is 2147483647.
@Sjoerd: You're right, my mistake. I corrected my answer. Forgot I was on my laptop. :-P

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.