0

Greeting, need help to solve this problem.

$x = 5;
$y = 19;
$z = 100;

This number must be in 4 digit only. Example if return 19 it must be 0019. How to added '0' in the beginning of variable.

output:
$x = 0005;
$y = 0019;
$z = 0100;
1
  • 5
    str_pad($value, 4, '0', STR_PAD_LEFT); Commented Mar 30, 2018 at 3:25

6 Answers 6

3

Use sprintf :

sprintf('%04d', 15);

Alternatively you can also use str_pad:

str_pad($value, 4, '0', STR_PAD_LEFT);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I always forget about sprintf. I edited it to put it in code blocks easier to read...
2

str_pad

$number = 19;
$val = str_pad($number, 4, '0', STR_PAD_LEFT);
echo $val;
// 0019

1 Comment

I don't like this answer, it's to obvious,. plus someone mentioned it in the comments... {sarcasm}. No it's good I love str_pad works good for a line separator in CLI eg. echo str_pad('', 64, '=') prints a line of 64 ========
1

Use str_pad()

$x = 5;
$y = 19;
$z = 100;
echo str_pad($x, 4, '0', STR_PAD_LEFT)."<br>";
echo str_pad($y, 4, '0', STR_PAD_LEFT)."<br>";
echo str_pad($z, 4, '0', STR_PAD_LEFT);

Output

0005
0019
0100

Comments

0

Try this out

    $output  =  substr('0000'.$Input, -4);

Comments

0

You guys took all the good answers

$x = 23;

while(strlen($x)<4)$x='0'.$x;

echo $x;

Outputs

0023

Test it online!

Sorry this is all that was left.

Comments

0
$x = 5;
$y = 19;
$z = 100;
$x= "000".$x;  
$y= "000".$y;
$z= "000".$z;`

This form is simple or

<?php 
$number=12443;
$format = number_format($number, 2, '.', '');
echo $format;
?>

1 Comment

You know if you do 4 spaces, it puts it in a bigger code block? But you have to put text (without 4 spaces) after it, to break out of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.