1

Im trying to generate barcode and i need it to be in 20 numbers. Barcode requires that reference must be in 20 numbers.

So if my reference is 67585 its must be 20 numbers like that 00000000000000067585

And if reference is 489382995463342 Barcode number must be in 20 numbers like 00000489382995463342

I tried this code but it's not working properly

str_pad(str_replace('', '',$reference), 20, '0', STR_PAD_LEFT);
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
coodienoobie
  • 129
  • 5
  • 13

3 Answers3

1

Try this-

str_pad($reference, 20, '0', STR_PAD_LEFT);

OR,

sprintf('%20d', $reference);
Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90
1

It seems fine (see http://3v4l.org/UKBqS), how are you viewing/inspecting the final value?

<?php
if ( ! defined('PHP_EOL')) {
    define('PHP_EOL', "\n");
}

foreach (array('67585', '489382995463342') as $test) {
    echo str_pad($test, 20, '0', STR_PAD_LEFT), PHP_EOL;
}
Anthony Sterling
  • 2,451
  • 16
  • 10
1

use sprintf

Docs Link for sprintf function.

http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02s", $num);
echo $num_padded; // returns 04
?>

PHP prepend leading zero before single digit number, on-the-fly

Community
  • 1
  • 1
Maz I
  • 3,664
  • 2
  • 23
  • 38