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 Link to comment https://forums.phpfreaks.com/topic/47817-solved-random-array-but-saving-key/ 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); ?> Link to comment https://forums.phpfreaks.com/topic/47817-solved-random-array-but-saving-key/#findComment-233640 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 Link to comment https://forums.phpfreaks.com/topic/47817-solved-random-array-but-saving-key/#findComment-233644 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. Link to comment https://forums.phpfreaks.com/topic/47817-solved-random-array-but-saving-key/#findComment-233647 Share on other sites More sharing options...
PC Nerd Posted April 19, 2007 Author Share Posted April 19, 2007 thankx ill try it now Link to comment https://forums.phpfreaks.com/topic/47817-solved-random-array-but-saving-key/#findComment-233652 Share on other sites More sharing options...
PC Nerd Posted April 20, 2007 Author Share Posted April 20, 2007 solved, thanks guys Link to comment https://forums.phpfreaks.com/topic/47817-solved-random-array-but-saving-key/#findComment-233709 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.