How to add zero before number in PHP?

Member

by darion , in category: PHP General , 10 months ago

How to add zero before number in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 5 months ago

@darion 

There are several ways to add leading zeros to a number in PHP. Here are a few options:

  1. Using str_pad() function:
1
2
3
$number = 123;
$paddedNumber = str_pad($number, 5, '0', STR_PAD_LEFT);
// Output: 00123


  1. Using sprintf() function:
1
2
3
$number = 123;
$paddedNumber = sprintf('%05d', $number);
// Output: 00123


  1. Using str_repeat() and substr() functions:
1
2
3
$number = 123;
$paddedNumber = substr(str_repeat('0', 5) . $number, -5);
// Output: 00123


  1. Using str_split() and implode() functions:
1
2
3
$number = 123;
$paddedNumber = implode(array_pad(str_split($number), 5, '0'));
// Output: 00123


I hope this helps! Let me know if you have any questions.