inwebdeveloper

Open Source Web Developers Resources

If you want to format a number with leading or trailing zeroes, you can use this method :

1. Use the printf( ) or sprintf( ) function

[php]
//Source : http://stackoverflow.com/a/6457950

$number = 9;
$paddedNum = sprintf("%04d", $number);
echo $paddedNum; // prints 0009

[/php]

2. Use the str_pad() function

[php]
//Source : http://stackoverflow.com/a/6457981

//$number = 9;
echo str_pad($number, 4, ’0′, STR_PAD_LEFT); // output: 0009

[/php]

OR

[php]

//Source : http://www.php.net/manual/en/function.str-pad.php#86404
function number_pad($number,$n) {
return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
}

echo number_pad($number,4);
[/php]

Categories: PHP 0 like

Leave a Reply