FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Filling an array with random input doesn't quite work
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Filling an array with random input doesn't quite work [message #185267 is a reply to message #185265] Sun, 16 March 2014 02:14 Go to previous messageGo to previous message
Jerry Stuckle is currently offline  Jerry Stuckle
Messages: 2598
Registered: September 2010
Karma:
Senior Member
On 3/15/2014 5:32 PM, Ben Bacarisse wrote:
> Thomas 'PointedEars' Lahn <PointedEars(at)web(dot)de> writes:
>
>> 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 :)
>
> Yes, but it's a shame about the extra ')'. I think
>
> $ayr = array_map(function () { return rand(60, 69); },
> array_fill(1, 40, null));
>
> is a little simpler.
>

Shorter, maybe - but arguably NOT simpler. Hand that code to a new PHP
programmer and he/she will have no idea.

It's generally better to code for clarity first.


--
==================
Remove the "x" from my email address
Jerry Stuckle
jstucklex(at)attglobal(dot)net
==================
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: readdir lists randomly
Next Topic: Nested PHP
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Wed Nov 27 21:23:55 GMT 2024

Total time taken to generate the page: 0.04272 seconds