sbonney Posted November 5, 2013 Share Posted November 5, 2013 This simple bit of code is meant to generate ten random numbers and store them in an array. They print out as they are generated and look fine. However, it appears that all values in the array are being set to the last number generated. This code is running online here. <?PHP function runtest() { $playerInit = array(); $numPlayers = 10; for ($i = 1; $i <= $numPlayers; $i++) { $playerInit[i] = mt_rand(1,10); echo " Player #".$i." rolled a ".$playerInit[i]."<BR>"; } echo "<BR>"; $i=1; while ($i <= $numPlayers) { echo " Player #".$i." rolled a ".$playerInit[i]."<BR>"; $i++; } } runtest(); ?> Any tips would be greatly appreciated. Thanks. Link to comment https://forums.phpfreaks.com/topic/283631-array-losing-its-values/ Share on other sites More sharing options...
DavidAM Posted November 5, 2013 Share Posted November 5, 2013 $playerInit[i] = mt_rand(1,10); Missing $ on the array subscript. You have the same problem in both echo statements. Turn on error reporting, these statements should be issuing errors (notices) about an undefined constant. Link to comment https://forums.phpfreaks.com/topic/283631-array-losing-its-values/#findComment-1457109 Share on other sites More sharing options...
sbonney Posted November 7, 2013 Author Share Posted November 7, 2013 Thank you! Such a simple thing, how did I keep overlooking that? Link to comment https://forums.phpfreaks.com/topic/283631-array-losing-its-values/#findComment-1457410 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.