$this = (new Soapbox())->shout(array_map('strtoupper', $opinions)); //Shaun's blog

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 detriment) to doing things this way; we're now making three calls to sprintf() on each iteration instead of two, and not gaining anything for our trouble. But suppose your for loop is more complex, and you're calling sprintf() more than three times per iteration, and for some reason you don't want to store the formatted number as a locally scoped variable, and... Well, I just thought it was a neat trick.

Recent articles

📰 Unusual HTTP POST traffic from

📰 Fast, but not so accurate (yet)

📰 autodiscover.xml as an Indicator of Attack

📰 Blocking Facebook's Tracking and Surveillance: A Comprehensive Approach

📰 Let's Encrypt Readies for Certificate Transparency with Embedded SCTs

📰 Evaluating DNSBL Effectiveness with Postfix Logs

📰 Russian/Ukrainian Referer Spam Campaign IPs

📰 Resolving subversion error E145001: Node has unexpectedly changed kind

📰 Installing PHP 7.2 with pthreads on CentOS 6

📰 LocalStorage kills another site, or: Working around Zap2it's new interface

📰 A new DNS geolocation service from PowerDNS

📰 Firefox's privacy.resistFingerprinting option reports a very old User-Agent (50.0)

▲ Back to top | Permalink to this page