Skip to content

Pad a string with zeros using PHP

Recently I had to create a code/username maker to fit into a certain type of pattern so that all “broker codes” (as they were called) followed the same path.
An example one looked like so:


The number needed to increment and I wanted to use the auto-increment feature in the mysql database table that was driving this data to make it.

This was easy but I ended up with a code that looked like this:


No zeros!

So I found a built in PHP function which I somehow managed to overlook for years and years and years.

The magic function this time around is called… str_pad() and I used it like this to get the result I was after:

$last_id = 1; /* $last_id is dynamically assigned from the mysql_insert_id() after the mysql_query() finishes, and we have a auto-increment value */ $brokercode = "HJTH".str_pad($last_id, 4, , STR_PAD_LEFT);
Code language: PHP (php)

See also  How to Bulk Move All Email from One Account to Another using the CLI
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x