Padding a number with zero in PHP

Mar 17, 2011

help with php

This really should be simpler than it is. Well, that isn’t entirely true because it really is simple – but it took me at least three google searches to find out how to do what I wanted, so I thought it was worth sharing. I first tried using str_pad and got nowhere but then found an example using sprintf.

The following code will take a number ($raw) and prefix it with two zeros.

$formatted = sprintf("%02d", $raw);