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


Me, elsewhere

GitHub
parseword
Miscellaneous public code

snuze
A PHP API client for Reddit

Twitter
@parseword
I don't tweet much

XMPP chat
xmpp@shaunc.com
(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

📰 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 23.225.141.70

📰 Website integrity monitoring through version control

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

▲ Back to top | Permalink to this page