PHP with prefix 0 for a number

Today when I try to generate the Student ID for a school project I meet a problem what I think almost us will meet. By the way, I figured out a very good way to solve it so that I decide to share to here.

PHP with prefix 0 for a number

My problem with PHP in number prefix 0

My customer want to generate the number like this

<year-4 digits><class name-string><ID – 4 digits>

With ID need to generate auto increase, if it is not enough 4 digits then put “0” as prefix to get it enough. It will look like this


Year: 2014

Class name: 10A1

ID: 0013

What we need to do is finding a good way to put “0” for enough 4 digits.

My solution

Ok, and this is the way I do, it ‘s very simple

With $studentID is the final result

$Y is the current year. You can generate it easy

$Y = date(‘Y’);

$C is the class name, you get it from your system.

And $ID is the number you generate from your system. You need to make sure it ‘s string before doing this.

$ID .= “”;

Final PHP code

Enjoy and good luck


  1. When I meet this problem, I don’t think PHP already supported the good function to do that, it ‘s really nice to save my code lines. Thanks for a great solution.

  2. Thanks man, good to know 🙂

  3. It seem you meet problem with code display!