Formatting an iterator within a `for` loop
Posted March 04, 2014
by shaun
I discovered by accident that PHP allows you to format the iterator in a for
loop with sprintf()
, as long as the result of sprintf()
can evaluate to the same numeric type as your step value. As a contrived example, consider the following loop used to build out the options in a "months of the year" select list:
$month = '<select name="month">';
for ($i = 1; $i < 13; $i++) {
$month .= '<option value="' . sprintf('%02d', $i) . '">' . sprintf('%02d', $i);
}
$month .= '</select>';
The same loop can be written this way:
$month = '<select name="month">';
for ($i = sprintf('%02d', 1); $i < sprintf('%02d', 13); $i = sprintf('%02d', ++$i)) {
$month .= '<option value="' . $i . '">' . $i;
}
$month .= '</select>';
That is, the formatting of $i
into a two-digit zero-padded integer is being done inside of the control block itself, instead of as a separate instruction inside the loop.
In this specific example, there's no benefit (and in fact there is some detri...