PHP - Array_rand Help?
Hello All,
I'm trying to work out how to use array_rand() to output a random value in an array. So i've tested it in a single array, and it works fine: $input1 = array("Link1", "Link2", "Link3", "Link4", "Link5"); $rand_keys = array_rand($input1, 2); echo $input1[$rand_keys[0]] . "\n"; However, I want 'Link1', 'Link2' etc to have their own SPECIFIC URL values, so i've tried declaring another array: $input1 = array("Link1", "Link2", "Link3", "Link4", "Link5"); $input2 = array('page.php','file.php','ends.php','smile.php'); //So 'Link1 = page.php, Link2 = file.php etc... $rand_keys = array_rand($input1, 2); echo 'The value for input 1 is: '.$input1[$rand_keys[0]] . 'and the url is '.??????????????.' "\n"; But can't work out how i'd grab this value - anyone kindly help? Similar TutorialsAlthough I found a way around it, I want to know, logically, why the behavior is so. // words.txt is a text file with dictionary words on each line $lines = file('words.txt'); // The goal is to pick two random words, 10 times. for($i = 0; $i < 10; $i++) { #shuffle($lines); <--- un-commenting this is the fix i found. $words = array_rand($lines, 2); echo "Words: " . $lines[$words[0]] . ", " . $lines[$words[1]] . "<br>"; } If i don't have shuffle() in there, I get two different set of words, not 10. ie (result from code above) Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Words: massacre , spear Words: frontiersman , kumquat Why is this? Hi, I have a function that pulls a random line from a text file and I would like to change it so it pulls a random line from a text file that contains a certain date, heres the current function : Code: [Select] function RandomLine($filename) { $lines = file($filename) ; return $lines[array_rand($lines)] ; } Any ideas on the best way to do this ? Many thanks. Hey guys, quick question. The array_rand() function. How random is it? I'm building an app in codeigniter where i'd need to return 2/6 keys from an array and store them in a DB. I don't want it to return a key that has already been returned. I'm sure logically there's always a chance that I could get back something that has already been returned. Also i'm using the function at the same time, so it isn't over any period of time or within different methods. Are there any other recommendations apart from array_rand() ? Thanks! |