Page 1 of 1

Shuffling arrays

Posted: Thu Jul 23, 2009 8:25 am
by gabor
Hi,
I'm writing an online testing system. I created an array with the answers:

Code: Select all

   //$i is the question number
        $answer[$i.'answer1']=$answer1;
        $answer[$i.'answer2']=$answer2;
        $answer[$i.'answer3']=$answer3;
        $answer[$i.'answer4']=$answer4
;[/color]

To mix the answers I use shuffle($array) like this:

Code: Select all

$answer=shuffle($answer);
[/color]

The correct answer was originally $answer1. Is there a way to find out which option in the shuffled array is $answer1? Or is there a way to shuffle and keep te original array keys?

Thank you for your help.

Re: Shuffling arrays

Posted: Thu Jul 23, 2009 9:30 am
by Mark Baker
First of all, shuffle() returns a boolean (success or failure) rather than the actual array. That's passed by reference rather than by value, so

Code: Select all

$answer=shuffle($answer);
will shuffle $answer, then overwrite it with true or false.
Use

Code: Select all

$shuffled=shuffle($answer);
if (!$shuffled) {
   //error
}
 
The correct answer was originally $answer1. Is there a way to find out which option in the shuffled array is $answer1? Or is there a way to shuffle and keep te original array keys?
Consider restructuring your array:

Code: Select all

$answer[$i]['answer1']=$answer1;
$answer[$i]['answer2']=$answer2;
$answer[$i]['answer3']=$answer3;
$answer[$i]['answer4']=$answer4

Re: Shuffling arrays

Posted: Fri Jul 24, 2009 12:36 am
by gabor
Thank you.