PC Nerd Posted April 19, 2007 Share Posted April 19, 2007 hi guys ive got an arrey: $Avail_Questions[]....... and i want to selet a random element, buti want to save the key with it im using shuffle() and it rnaodmizes the keys and the values....... so how can i save the key? i had trouble with array_rand(), but im happy to go back to it..... thanks so much Quote Link to comment Share on other sites More sharing options...
Glyde Posted April 19, 2007 Share Posted April 19, 2007 Well, I'm not going to try to figure out why array_rand gave you problems, but you could try: <?php function getRandom($array) { $keyList = array_keys($array); shuffle($keyList); $value = $array[$keyList[0]]; return $value; } $array = array('test' => 'asdf', 'dfgd', 't42' => 'sdf'); print getRandom($array); ?> Quote Link to comment Share on other sites More sharing options...
MadTechie Posted April 19, 2007 Share Posted April 19, 2007 could use array_keys to get the keys and then shuffle that array and use that ie <?php $Quests = array("1" => "Q1", "2" => "Q2", "3" => "Q3", "4" => "Q4", "5" => "Q5" ); $RandQ = array_keys($Quests); shuffle($RandQ); foreach($RandQ as $R) { echo $Quests[$R]; } ?> **UNTESTED Quote Link to comment Share on other sites More sharing options...
linuxdream Posted April 19, 2007 Share Posted April 19, 2007 <?php $data = array('somethign', 'nothing', 'again', 'and again', 'without', 'anything'); $rand = rand(0, count($data)-1); echo $data[$rand]; ?> Might work too. Quote Link to comment Share on other sites More sharing options...
PC Nerd Posted April 19, 2007 Author Share Posted April 19, 2007 thankx ill try it now Quote Link to comment Share on other sites More sharing options...
PC Nerd Posted April 20, 2007 Author Share Posted April 20, 2007 solved, thanks guys Quote Link to comment 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.