Shuffling arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gabor
Forum Newbie
Posts: 5
Joined: Sat Jul 11, 2009 6:59 pm

Shuffling arrays

Post 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.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Shuffling arrays

Post 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
gabor
Forum Newbie
Posts: 5
Joined: Sat Jul 11, 2009 6:59 pm

Re: Shuffling arrays

Post by gabor »

Thank you.
Post Reply