Zero padded numbers in PHP

Snippet

If you need to pad a numbers/strings with zeros and make them of a default length, then you could try some of the ways documented below.

First example:

downloadcopy
<?php
function getZeroPaddedNumber($value, $padding) {
       return str_pad($value, $padding, "0", STR_PAD_LEFT);
}

echo getZeroPaddedNumber(143, 4); // 0143
echo getZeroPaddedNumber(12, 4); // 0012

Second example:

downloadcopy
<?php
function getZeroPaddedNumber($value, $padding) {
       return sprintf("%0".$padding."s", $value);
}

echo getZeroPaddedNumber(143, 4); // 0143
echo getZeroPaddedNumber(12, 4); // 0012