Jump to content


Photo

Unexpected Array_Rand Behaviour


  • Please log in to reply
2 replies to this topic

#1 leke

leke

    Advanced Member

  • Members
  • PipPipPip
  • 39 posts
  • LocationFinland

Posted 25 November 2012 - 03:11 AM

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, 25 November 2012 - 03:12 AM.

! -- n00b Alert -- !

#2 requinix

requinix

    Transforming Moderator

  • Moderators
  • 6,030 posts
  • LocationWA

Posted 25 November 2012 - 07:40 AM

When you said there were no empty lines you lied. Unknowingly. There's a newline at the end of your file and after that is an empty line.

Also, file is much better for getting lines from a file.

#3 leke

leke

    Advanced Member

  • Members
  • PipPipPip
  • 39 posts
  • LocationFinland

Posted 25 November 2012 - 01:06 PM

Wow, it appears I over complicated things :o
Thanks for the file suggestion.
$movie_title_file = '4-movies.txt';
$movie_title_db = file($movie_title_file);
shuffle($movie_title_db);
print_r($movie_title_db);

! -- n00b Alert -- !




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com