Re: Filling an array with random input doesn't quite work [message #185254 is a reply to message #185250] |
Fri, 14 March 2014 22:07 |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma:
|
Senior Member |
|
|
Daniel Pitts wrote:
> On 3/12/14 10:18 AM, richard wrote:
>> $x=1;
>> while ($x<40){
>> $yr=range(60,69);
>> shuffle($yr);
>> $ayr[$x]=$yr[$x];
>> echo $ayr[$x]."<br>";
>> $x++;
>> }
>>
>> I am attempting to load an array based upon the range of numbers 60
>> through 69.
>> The array will have 40 items.
>> This code produces 9 items just fine.
>> The rest of the array is empty.
>> What am I missing?
>
> for ($x = 1; $x < 40; ++$x) {
> $ayr[$x] = rand(60, 69);
> }
>
> So much simpler, more efficient, and actually correct.
No, this will produce an array of only 39 elements, assuming there was not
already one. This can be easily fixed, of course.
Still,
$keys = range(1, 40);
$ayr = array_combine($keys, array_map(function () {
return rand(60, 69);
}, $keys)));
is much more elegant :)
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
|
|
|