How to zero fill a number with PHP

Zero filling (or zero padding) is when you pad a value on the left side to a specific length. This is something you will commonly see in database schemas for integer columns. But what if we’re not working with data that’s already zero filled by a database? All we have to do is take advantage of PHP’s type juggling and pad the variable with str_pad:

$variable = 123
$zerofill = 10

echo str_pad($variable, $zerofill, '0', STR_PAD_LEFT // 0000000123

Now we have a zero filled value to use as we please. Comes in handle when displaying a unique ID integer as tabular data, keeps everything nice and uniform looking.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.