Archive for March 8th, 2007

The error nobody spotted

… or maybe they were just too polite to say.

I’m currently working on the draft of a new book about PHP, and decided to create a form to demonstrate the effect of the various arithmetic operators. I used the same set of examples that I’ve stuck with ever since Foundation Dreamweaver MX 2004. The example for modulo division is $x % $z, where $x is 20 and $z is 4.5. Since modulo gives you the remainder of a division, the result is obviously 2.

Well, at least that’s what I thought. It’s mathematically correct, so nobody ever questioned it. Imagine my surprise, then, when I fed this example into my form and the result came back as 0. Had I stumbled across a PHP bug?

I hunted around on the official PHP site, and couldn’t find anything. So I did some more tests. When I played with integers, modulo worked exactly as I expected. It’s just with decimal fractions that it behaved oddly.

Finally, I consulted Programming PHP by Kevin Tatroe and Rasmus Lerdorf, which reveals that, in PHP, the modulo operator converts both numbers to integers before performing the calculation. As a result, 4.5 was being rounded up to 5. Hence my mistake.

It’s nice to discover an error in one of your own books before others point it out, but it’s a bit embarrassing to have made the same mistake in four books. :( Strange that it’s not mentioned in the PHP manual, either.

6 comments March 8th, 2007


Calendar

March 2007
M T W T F S S
« Jan   Apr »
 1234
567891011
12131415161718
19202122232425
262728293031  

Posts by Month

Posts by Category