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

Edited by leke
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.