How to Formatting a number with leading Zeros in PHP

In this post i show how to display number with leading zero like date and time.

Following PHP Function full fill our Needs

sprintf()

Why use sprintf()

It’s Return a string produced according to the formatting string format.

For Brief Details about sprintf() : http://php.net/manual/en/function.sprintf.php

Example :

<?php
$cnumber = 8;
$numwithzero = sprintf("%02d", $cnumber);
echo $numwithzero; // returns 08
?>

if your want to increase zeros use following (I increase three zero before Number)

<?php
$cnumber = 8;
$numwithzero = sprintf("%04d", $cnumber);
echo $numwithzero; // returns 0008
?>

 

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *