Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.