I want to generate a series of serial numbers like CHN000001,CHN000002,CHN000003
, etc using PHP. If there are 100 numbers, then the last one should be like CHN000100
. If it's 1000, then the serial should look like CHN001000. Can anyone tell me how to implement the "for" loop for this process?
Asked
Active
Viewed 5,428 times
0

Michael Petrotta
- 59,888
- 27
- 145
- 179

Basim Sherif
- 5,384
- 7
- 48
- 90
-
1`+` - is how to add numbers in php, `.` - is how to concatenate strings in php, and here is [`for`](http://nz.php.net/manual/en/control-structures.for.php) documentation – zerkms Jul 20 '12 at 04:44
-
What about fancying things up a little? You could encode your serial numbers in [base 36](http://en.wikipedia.org/wiki/Base_36) or including a check-digit for [Luhn validation](http://en.wikipedia.org/wiki/Luhn_algorithm)? – ghoti Jul 20 '12 at 04:53
-
2Er, insane? Really? Did you SEE your question? What code are we supposed to help you fix? – ghoti Jul 20 '12 at 04:54
-
1Thanks! I'll continue to practice my insanity in an effort to improve the quality of StackOverflow content. BTW, you've had multiple downvotes, offset by a couple of upvotes. – ghoti Jul 20 '12 at 04:59
2 Answers
10
The following should work. The function you use is sprintf
for($i=1;$i<=100;$i++)
echo sprintf("CHN%06d", $i)." ";

Anirudh Ramanathan
- 46,179
- 22
- 132
- 191
5
$x = 0;
while ($x <= 999999)
{
$numZero = 6 - strlen($x);
echo 'CHN'.str_repeat('0', $numZero).$x;
$x++;
}

Stegrex
- 4,004
- 1
- 17
- 19
-
@BasimSherif I'd also look at DarkXphenomenon's solution as well. It's more elegant than mine. – Stegrex Jul 20 '12 at 05:00