How to zero fill a number with PHP

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles