Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Jackie Jen
2,723 Pointsgenerate auto increment alphanumeric strings
Below is my code
<?php
$length = 4;
$id = '';
for ($i=0;$i<$length;$i++){
$id .= rand(1, 9);
}
echo $id;
?>
right now i only able to generate randomly of 4 digits number. But how can i add character in the 4 digits like 'AAA0001' then it automatucally increase to 'AAA9999' and start with new character ' AAB0001'.
I have no idea on it,please advice.
2 Answers

john appleseed
2,568 PointsHey!
$num_of_ids = 10000; //Number of "ids" to generate.
$i = 0; //Loop counter.
$n = 0; //"id" number piece.
$l = "AAA"; //"id" letter piece.
while ($i <= $num_of_ids) {
$id = $l . sprintf("%04d", $n); //Create "id". Sprintf pads the number to make it 4 digits.
echo $id . "<br>"; //Print out the id.
if ($n == 9999) { //Once the number reaches 9999, increase the letter by one and reset number to 0.
$n = 0;
$l++;
}
$i++; $n++; //Letters can be incremented the same as numbers. Adding 1 to "AAA" prints out "AAB".
}
The previous code would print out the following,
AAA0000 AAA0001 AAA0002 AAA0003 AAA0004 AAA0005 AAA0006 AAA0007 ...
Sprintf is very useful in situations like this, so I'd recommend reading more about it in the documentation. http://us2.php.net/manual/en/function.sprintf.php
Good luck!

Jackie Jen
2,723 PointsThanks alot..about the sprint function