2

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 :)

Juvar Abrera
  • 465
  • 3
  • 10
  • 21

4 Answers4

4

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);
Starx
  • 77,474
  • 47
  • 185
  • 261
2
$i = 1;
$i++;
printf("%04d", $i); // 0002
  • printf - output a formatted string
  • %04d - echo a 4 digit number, pad with 0's
flowfree
  • 16,356
  • 12
  • 52
  • 76
0

try this

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

read the documentation here : http://php.net/manual/en/function.str-pad.php

rjmcb
  • 3,595
  • 9
  • 32
  • 46
0
$input = 0001;
echo str_pad(++$input, 4, "0", STR_PAD_LEFT); 
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153