Search code examples
phpvariablesintegerprefixoctal

How to add zero/zeroes at the beginning of an integer value in PHP?


I've a variable titled $value as follows :

$value = 5985;

If I echo 05985; it prints 15. I understood that PHP considers this number as octal and prints 15 but I don't want 15 I want leading zero/zeroes prefixed to a value contained in a variable $value.

But I want to make it five or say six digits long. In that case I need to add leading zero/zeroes to the value contained in a variable $value. When I add those leading zeroes and echo the variable $value it should look like as follows :

05985; //If I want five digit number
005985; //If I want six digit number

I searched and tried following approach but it didn't work out.

str_pad($value, 8, '0', STR_PAD_LEFT);
sprintf('%08d', $value);
echo $value;

So can someone please suggest me how to do that?

Thanks.


Solution

  • Sprintf does not directly change the value of its second parameter, it returns the result. Try

    $value = sprintf('%08d', $value);