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

Me, elsewhere

Miscellaneous public code

I don't tweet much

XMPP chat
(Pidgin, Miranda, Swift, etc.)

Perfect is the enemy of good enough.

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

📰 Using WITH_META_MODE and ccache for FreeBSD build boosts

📰 Resolving subversion error E000013: Unable to create pristine install stream

📰 Enhancements to SmokePing's AnotherDNS probe

📰 Generating vanity DNSSEC key tags

📰 DDoS involving forged packets from

📰 Website integrity monitoring through version control

📰 SpamAssassin 3.4.2 fixes security problems, adds HashBL and phishing plugins

📰 Bug or turf war? ICQ via Pidgin now fails with "startOSCARSession: Request Timeout"

📰 🎂

📰 SFSQuery, a PHP class to query the StopForumSpam API and DNSBL

📰 Resolving portmaster error "pkg-static: automake-1.16.1 conflicts with automake-wrapper-20131203"

📰 Resolving LibreNMS error "RuntimeException: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths"

📰 Fast, but not so accurate (yet)

📰 autodiscover.xml as an Indicator of Attack

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

▲ Back to top | Permalink to this page