After seeing this reddit post it got me thinking of all of the very terrible code PHP has let me write over the years. Now that I no longer work in PHP I feel like maybe it's time to impart on the world the stupidity in my ways.

Numbers Aren't Always Numbers

There's this masterpiece of code that all PHP devs should be aware of: PHP can divide by zero. This type of math on a string is the source of one of my most confusing bugs.

$total = 132.0000102; // some number
$cleantotal = number_format($total_total, 2);

$cleantotal is a string, not a numeric value. So when I would perform math on it it sort of kinda worked. It worked until you had more then $1,000 worth of products in your cart, at which point PHP's built in string to number converter would return 0, instead of an error. I fixed this by just changing to using number_format() only right before display. But since $1,000 orders were so rare it was very difficult to realize that this was what was happening.

Casting to int Can Stack Overflow

While testing the same site as the above bug we kept crashing the server and required a full reboot whenever one of the designers would add items to his cart. After a lot of trial and error it was tracked down to a single cast.

public function update($key, $qty) {
    if ((int)$qty && ((int)$qty > 0)) {
       $this->session->data['cart'][$key] = (int)$qty;
    } else {

What he had done was just type in an arbitrarily large number to the quantity field. $qty came into the function as a string, so when it was cast to int it stack overflowed. Whats extra funny about this is there's no reason to cast to int, simply doing is_numeric($qty) && $qty > 0 fixed this bug. This was in OpenCart, not sure this issue still exists as when we found it I reported it to the developer.

What Irks Me

The fact that both of these critical bugs could have been caught at compile time with any strongly typed language does not escape me. Indeed it's one of the reasons that I've enjoyed my move to C# so much more as time has gone on.

At my current job we have a lot of legacy code in Classic ASP, which suffers from the same lax typing requirements of PHP and were so many errors I'm forced to fix are introduced. Asking for an array key that doesn't exist? That's not an error, that's an empty string!

About Author

Siva Katir

Siva Katir

Programmer working at MGM Solutions in Bellingham Washington.