Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer into X characters string in PHP [duplicate]

I have an integer that I need to convert into a 4 digits string. I know the integer number is between 1 and 9999. If the number is 4, I want the output string to be "0004". If the number is 134, I need the string output as "0134" and so on.

What would be the shortest most elegant way of achieving this in PHP? Thank you.

like image 358
Marcos Buarque Avatar asked Feb 13 '26 12:02

Marcos Buarque


1 Answers

I would use sprintf():

$string = sprintf( "%04d", $number);

Using this demo:

foreach( array( 4, 134) as $number) {
    $string = sprintf( "%04d", $number);
    echo $string . "\n";
}

You get as output:

0004
0134
like image 185
nickb Avatar answered Feb 15 '26 01:02

nickb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!