CodeSOD: Another Iteration
One of the "legacy" PHP applications needed a few bugfixes. "Legacy" in this case, means "written by a developer who doesn't work here anymore", so mostly everyone tried to dodge getting those bugfixes assigned to them. Joe was taking a three day weekend at the time, so a helpful co-worker assigned the tickets to him.
The code wasn't an absolute disaster, but it suffered from being written by a "smart" programmer. Since they were so smart, they couldn't just do things using the basic language constructs, they had to find clever ways to abuse them.
For example, why would you write a for loop, with a counting variable, when you could do this instead?
$a = array_fill(0, 100, 1);foreach($a as $i){ //whatever}
Yes, they populate an array with the range of their loop, and then just foreach over the array. This pattern was standard for this developer, nary was a traditional for loop to be found.
Now sometimes, this developer also needed to know which iteration they were on, so sometimes they would capture the array index, like:
$a = array_fill(0, 100, 1);foreach($a as $i => $one){ //whatever with $i}
This is basically the same as above, except the key (or index) of the element in the array gets stored in $i, while the value gets stored in $one. Now, if you're thinking to yourself that array_fill means that there's a direct relationship between these two values, so that's completely unnecessary, you win a prize. The prize is that you don't have to work on this code.
As an aside, while I was checking the specific PHP syntax for foreach, I found this caveat to manipulating arrays by reference, which cautions about some absolutely bizarre side-effects. That has nothing to do with this code, but just demonstrates another way in which PHP can harm you.
[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!