Whats wrong with this PHP??

Soldato
Joined
2 May 2004
Posts
19,950
Hi,

Someone asked me if I could print out the numbers 1-32 on a page, separated by <br> randomly.

I did this:

Code:
<?php
$input = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32);
$randKeys = array_rand($input, 32);

for($i=1; $i<33; $i++)
{
  echo 'Number'.$i.': '.$input[$randKeys[$i]].'<br />' . "\n";
}
?>

Most of it works alright, but for some reason when it comes to echoing the array randomly it misses out a single array, so I get 31 on the page instead of 32.

Any ideas why please?

Thanks,
Craig.
 
Arrays by default start at 0.

Code:
<?php
$input = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32);
$randKeys = array_rand($input, 32);

for($i=0; $i<32; $i++)
{
	$number = $i + 1;
  	echo 'Number'.$number.': '.$input[$randKeys[$i]].'<br />' . "\n";
}
?>

Probably a cleaner fix but it's late and I'm in the middle of other code. :)
 
Back
Top Bottom