PHP Build a Basic PHP Website Listing and Sorting Inventory Items Random Fun with Arrays

Daniel Fitzhugh
Daniel Fitzhugh
7,025 Points

Why 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:

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
Michael Cook
15,146 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():

Basically, 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 $keys. So let's say you have an array $myArray that has a count of int 10. You want 3 random $values. 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:

$myArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

$randomKeys = array_rand($myArray, 3);

foreach ($randomKeys as $key) {
  echo $myArray[$key];

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.