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

Me, elsewhere

Miscellaneous public code

A PHP API client for Reddit

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

📰 Caveat with Vantec SATA/IDE to USB 2.0 Adapter and Macrium software

📰 Jay Niffley, Man of Mystery

📰 Compiling Doxygen on FreeBSD without LaTeX and Ghostscript

📰 Introducing Snuze, a PHP client for the Reddit API

📰 jisusaiche: Java's installer telemetry

📰 BIND client log error "query_find: query_getdb failed"

📰 Resolving "The lang/perl5.24 port has been deleted: Has expired" portmaster error

📰 Armagaddon2 interim fix for Firefox 56 and other old versions

📰 Strange DNS queries: qname "miep", qtype ANY

📰 Undeliverable as addressed: A massive broken spam campaign?

📰 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

▲ Back to top | Permalink to this page