Use PHP sprintf to pad leading zeros

A simple way to use sprintf in PHP to pad a number with leading zeros.

<?php

// Pad the number 2 with zeros to get a 5 char (total) length string
$n = 2;
$n_padded = sprintf('%05d', $n);

// EXAMPLES

// Pad month/year to 2 digits in credit card form dropdown
$year_from = (int)date("y");
$year_to = $year_from + 6;
for($i = $year_from; $i <= $year_to; $i++) {
	$year = sprintf('20%02d', $i);
	echo "<option value="{$i}">{$year}</option>";
}

// Making up unique (Australian) mobile numbers for testing
$n = 0;
do {
	$mobile = sprintf('04%08d', $n++);
} while(is_existing_mobile($mobile));
comments powered by Disqus