leke Posted November 25, 2012 Share Posted November 25, 2012 (edited) 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 November 25, 2012 by leke Quote Link to comment https://forums.phpfreaks.com/topic/271138-unexpected-array_rand-behaviour/ Share on other sites More sharing options...
requinix Posted November 25, 2012 Share Posted November 25, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/271138-unexpected-array_rand-behaviour/#findComment-1394935 Share on other sites More sharing options...
leke Posted November 25, 2012 Author Share Posted November 25, 2012 Wow, it appears I over complicated things 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); Quote Link to comment https://forums.phpfreaks.com/topic/271138-unexpected-array_rand-behaviour/#findComment-1394980 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.