Many years ago, DJ got his start doing odd web development jobs for a low hourly rate. He was only 19 when he got started, and what he lacked in experience he made up for in being cheap to hire.

As I said, that was many years ago, and he has since learned a lot. But he still has some code from his very first "someone paid me for this" project. This particular function needed to pick a random bit of content from their database to display in the "right side" banner area. This is how DJ implemented it.

// Create an array of all the ID's used
$int = array();
$query = $sql->query("SELECT * FROM rightside");
while($row = $sql->objects('',$query)) {
    $int[ $row->id ] = $row->id;
    if ($row->id > $max) {
        $max = $row->id;
    }
}
                
// Find a random ID that has been used
$x = false;
while ($x == false) {
    $rand = rand(0,$max);
    foreach ($int as $thing) {
         if ($thing == $rand) {
 $x = true;
         }
    }
}

$query = $sql->query("SELECT * FROM rightside WHERE id = ".$rand);

We start by building an array. Then we query the database for all the content. We get all the rows and columns, butw e only are interested in one- the id. We create a sparse array, where the index of the item is the item's value. We also track the max.

Once we've got that, we start a loop. Inside that loop, we generate a random number, check if it's in our array by doing a foreach across the array, and if it is, we break the loop- we've found our random content. If it's not, we keep trying until we score a hit.

Finally, we construct our query with string concatenation and grab the content we want to display.

Now, as a true confession, there's an element of caveat emptor here; if you're hiring the kid from the local college and paying them a few bucks an hour, this is the kind of thing you get.

Is the code terrible? Yes, even by early-00s PHP standards. Is it really DJ's problem, though? No. I'd hope any of us would look back at the code we wrote when we were 19, and shudder. It means we've learned something in the interim.

For this confession, I say there's no need to atone. Hopefully everyone learned a lesson, especially the company trying to hire programmers on the cheap.

[Advertisement] Picking up NuGet is easy. Getting good at it takes time. Download our guide to learn the best practice of NuGet for the Enterprise.