
Daniel Fitzhugh
8,757 PointsWhy does array_rand() return a "meta-array" of keys, and not just the original array with a reduced number of items ?
I noticed a recurring theme with the videos in this course regarding how to "filter" or "select a subset" from a master array. I've seen the same confusing technique in both of these videos:
https://teamtreehouse.com/library/random-fun-with-arrays https://teamtreehouse.com/library/sorting-multidimensional-arrays
The teacher always seems to create a "meta-array" of keys, and then juggles the parameters (in a really confusing way) to get the results that she wants.
Would it not be easier --- especially for this task, "Random fun with arrays" --- if array_rand() just produced an array which was similar in structure to the master array, which we could then iterate through using a "foreach" loop, without having to do all of the confusing parameter juggling that the teacher does whenever she uses her preferred technique ?
Sorry if this is confusing.... it confuses me also :)
Michael Cook
18,077 PointsMichael Cook
18,077 Points"Sorry if this is confusing.... it confuses me also :)"
Yeah, it is confusing. I was confused too with a lot of these videos and I plan to go back and re-watch some of them, just for the satisfaction of really getting it. But ultimately, I think its just her way of doing it that's confusing and not the concept itself. I consistently use
$key => $value
when I am working with associative arrays, and the consistency helps prevent confusion, but at times she doesn't seem to be consistent.Also, I really recommend reading the PHP docs often. At first I found them confusing but then I read an article explaining how to read the docs, and now I read them all the time. They really clarify things, which is what they're supposed to do.
Here are the docs for
array_rand()
: http://php.net/manual/en/function.array-rand.phpBasically, if you just want a single random item from an array, it will spit out one random
$key
that you can use to access the associated$value
. If you want more than one random item in the array, it will return an array of random$key
s. So let's say you have an array$myArray
that has acount
ofint 10
. You want 3 random$value
s. You could do$randomKeys = array_rand($myArray)
and then iterate through$randomKeys
with a foreach loop and do whatever you want with the random values from$myArray
like this:I hope this makes sense and I hope I actually helped clarify this for you :P. Not sure if this answer will help at all.