It’s tempting to pick on PHP, because PHP is a terribly designed language. At the same time, there’s an air of snobbery and elitism in our mockery of PHP. I mean, half the Web runs on PHP, so how bad can it be? These examples could easily have been written in nearly any other language, and they’d be just as bad in those languages too. Is it fair to single out PHP? Perhaps not, but each of these examples does nothing- or nearly nothing- which may very well be PHP’s greatest asset.

As a case in point, Ethan inherited some code. It needs to count how many sub-directories there are in a certain directory.

    $dir = opendir("/var/www/media/docs/");
    $nCount = 0;
    while($imagename = readdir($dir)) {
        if (strlen($imagename)>2 && is_dir("/var/www/media/docs/" . $imagename)) {
            $foldernames[] = $imagename;

We could pick on hard-coded strings and misleading, but for the most part, this code doesn’t seem too unreasonable. That is, until you look at the expression strlen($imagename)>2 in that if condition. What on Earth is going on there? Well, Ethan wondered the same thing. After some research, he managed to figure it out- there was a folder called “HR” that the original developer didn’t want indexed by this code. If you don’t think about it, this is much more efficient than an equality test, because this only has to look at every character in one string, not two.

Well, that code definitely does something. Is there some code that doesn’t do anything? Well, what about some code that doesn’t do anything useful? Betty learned about this error handling convention from a very expensive contractor.

    try {
        // code
    } catch (Exception $e) {
        throw new Exception($e->getMessage());

At least we know every exception is being handled… except the last one.

That still does too much. Is there any PHP code that’s even safer- and by safer, I mean “more useless”? Well, what about this shopping cart system David C found?

    $pids = array();
    foreach ($scratch_products as $product_data) {
        $pids[] = $product_data['productid'];

Now there’s the stuff. Create the array, populate it, and destroy it all in three lines. It would have worked great, too, if not for the fact that some code elsewhere in the program expected $pids to exist.

[Advertisement] Release! is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!