Format numbers with leading and trailing zeros in PHP

PHP provides str_pad() to add a string to a certain length with another string. Another way is to use sprintf() with formatting patterns.

Pad leading zeros to get exactly 3 digits:

$value = 12;
sprintf('%03d', $value);                    // 012
str_pad($value, 3, '0', STR_PAD_LEFT);      // 012



Posted in PHP