May 24, 2012

Numbering with prefix of zero in PHP

Question by Juvar Abrera

Is it possible in PHP to echo out a number with zeroes at the beginning?

For example

<?php

$i = 0001;
$i++;
echo $i;

?>

And when it print out, I want it to be like.

0002

Is it possible? Thanks 🙂

Answer by Starx

Yes, it is possible. You can do this using str_pad() method. Basically, this method adds a given value till a required length is achieved.

A Basic example of this would be:

echo str_pad($i, 4, "0", STR_PAD_LEFT); 

Here,

  • 4 represents the output length
  • "0" represents the string used to pad, till the length is achieved.

Demo Example:

<?php
$i = 0001;
$i++;
echo str_pad($i, 4, "0", STR_PAD_LEFT);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!