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:
[code lang=”bash”]
HJTH0001
[/code]

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:
[code lang=”bash”]
HJTH1
[/code]

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:
[code lang=”php”]
$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, 0, STR_PAD_LEFT);
[/code]

Related Posts

Run Javascript is a Chrome Extension that allows you to run custom Javascript each time you visit a website. It is particularly useful to web developers and people who like to tamper with websites they Read more…

Cyber-attacks do not always originate from outside of the target organisation. Veritably around twenty-five percent of all data breaches occur from the inside, from employees or trusted individuals within the organisation (TechBeacon, 2018). Employees that Read more…

Squid is a proxy software that allows a computer without internet access to proxy through another computer that does have internet access. Squid is very easy to get setup and the computer that needs internet Read more…