7

For example, I have this format: $s_number = "12"; And for this input, I need 0012 as the output:

Another example:

Input $s_number = "3"; Output: 0003

Every time I need 4 digits I would like this to happen.

sikrew
  • 7
  • 7
Martelo2302
  • 81
  • 1
  • 2
  • 5
  • 1
    `printf` can already do this: `printf("%04d", $number)`. There's also `sprintf` if you want the result in a string. – Jon Mar 05 '13 at 21:23
  • What have you tried? Did you try using something like sprintf (http://www.php.net/manual/en/function.sprintf.php) or just prepending text based on the length of the string? – Mike Mar 05 '13 at 21:23

3 Answers3

16

It won't be a number (but a string), but you can do that using str_pad. In your examples:

$s_number = str_pad( "12", 4, "0", STR_PAD_LEFT );
$s_number = str_pad( "3", 4, "0", STR_PAD_LEFT );
Vivienne
  • 600
  • 1
  • 3
  • 12
14

Use str_pad() for that:

echo str_pad($number, 4, '0', STR_PAD_LEFT); 
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
2

You can achieve this easily by using phps' printf

<?php
$s_number = '12';
printf("%04d", $s_number);
?>

Hope this helps

Mic1780
  • 1,774
  • 9
  • 23
  • ah thanks. Totally forgot they printf also prints it out (stupid of me cus it is also in the name of the function) – Mic1780 Mar 05 '13 at 21:29