Jump to content

[SOLVED] random array, but saving key


PC Nerd

Recommended Posts

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

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);
?>

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.