Reputation: 1333
In this thread, Pudge601 was so kind as to offer a solution to my problem: Php/MySQL random data (musical pitch) sequences
By substituting static values for random ones, I figured out how the while loop works. However, I am still trying to understand this line:
$dist = $dists[$index][array_rand($dists[$index])];
I can understand it when I substitute (for example)
$dist = $dists[$index][0]
Which retrieves the first array value from one of the nested arrays. BUT, I do not see how this portion:
[array_rand($dists[$index])];
Produces one of the desired values.
It does not seem to corresponds to the description here: http://php.net/manual/en/function.array-rand.php Perhaps the syntax is different when using the multidimensional array in this context? In any event, I'm just not getting it. If someone could help me make the translation to 'english', I'd be thankful!
Upvotes: 0
Views: 1440
Reputation: 1333
This same question was later resolved in this discussion: http://www.codingforums.com/showthread.php?t=296450
Answer: in $dist = $dists[$index][array_rand($dists[$index])];
, the first use of $dists[$index]
localizes the result to one of the first-nested arrays, and the second use makes sure that it is that same array that the array_rand function is picking from.
Upvotes: 0
Reputation: 173562
The code should be read as:
$arr = $dists[$index]; // select array from $dists element at index $index
$key = array_rand($arr); // get key of a random element
$dist = $arr[$key]; // get element value
From the documentation:
If you are picking only one entry,
array_rand()
returns the key for a random entry.
Upvotes: 2