Skip to content
PHP Logo

How can the sprintf() function in PHP be used to format integer values with leading zeros?

When formatting integer values with leading zeros in PHP using the sprintf() function, you can specify the width of the output by using a format specifier like '%04d'. This format specifier will ensure that the integer value is padded with zeros to a total width of 4 characters. This is useful when you need to display numbers with a consistent length, such as for displaying timestamps or IDs.

php
$number = 7;
$formatted_number = sprintf('%04d', $number);
echo $formatted_number; // Output: 0007