Jump to content

Unexpected Array_Rand Behaviour


leke

Recommended Posts

I have a file with four lines of text (no empty lines).

Apocalypto (2006)

Doubt (2008)

The Skin I Live In (2011)

Tucker and Dale vs Evil (2010)

and I want to grab four random keys from it...

php > $movie_title_file = "4-movies.txt";
php > $access_movie_title_db = file_get_contents($movie_title_file);
php > $movie_title_db = explode("\n", $access_movie_title_db);
php > $random_index = array_rand($movie_title_db,4);
php > shuffle($random_index);
php > print_r($random_index);
Array
(
[0] => 4
[1] => 1
[2] => 0
[3] => 2
)

as you can see, the results range form 0 to 4. That's five though and if I wanted to use the results to print out the index key to that line, then

echo $movie_title_db[$random_index[0]];

would print nothing because the $movie_title_db only has 0 to 3 (or 4) items.

 

How come array_rand works like this?

 

Thanks :)

Link to comment
https://forums.phpfreaks.com/topic/271138-unexpected-array_rand-behaviour/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.