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.
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
201410A10013
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
$studentID = $Y . $C . sprintf("%04s", $ID);
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
$Y = date('Y'); $C = "10A1"; // change to your class $ID = 13; // change to your ID $ID .= ""; // make sure it 's string $studentID = $Y . $C . sprintf("%04s", $ID);
Enjoy and good luck
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.
What type of your way before using this article, man?
Thanks man, good to know 🙂
It seem you meet problem with code display!
What do you mean, jackie99?