Hi, I have an array $quest for ( $count = 0; $count <= 99; $count++) { $quest[$count]=mysql_fetch_array($result,MYSQL_NUM);; } $quest is a 2d array.For instance $quest[0][0] contains a question $quest[0][1] to $quest[0][5] each contains an answer choice for the question only one of which is correct. I want to randomly shuffle all the answer choices($quest[0][1] to $quest[0][5]) but let the question remain at $quest[0][0]).How can I do that? I know there is a function called shuffle() but shuffle(),shuffles the entire array.I just want to shuffle all elements of a particular array except for the first one. Thanks Hemant
Thats true, but you can limit the shuffle excluding 0 so it will be 1-5, something like this, might help: <?php $quest[0][0] = "Question"; $quest[0][1] = "Answer 1"; $quest[0][2] = "Answer 2"; $quest[0][3] = "Answer 3"; $quest[0][4] = "Answer 4"; $quest[0][5] = "Answer 5"; echo $quest[0][0]; $answer = range(1, 5); shuffle($answer); foreach ($answer as $answer) { echo "<br />",$quest[0][$answer]; } ?> PHP: Will echo out: Question Answer 2 Answer 1 Answer 3 Answer 4 Answer 5 Code (markup):
You can try this.. <?php $_quest = $quest; $quest = array(); foreach($_quest as $idx=>$q){ shuffle($q); $quest[$idx] = $q; } ?> Code (markup):
You should really modify the code that builds the array to begin with if you can. This however, will work with an existing array. <pre><?php $quest = array( array( 'Question One', 'Answer 1:1', 'Answer 1:2', 'Answer 1:3', 'Answer 1:4', 'Answer 1:5', ), array( 'Question Two', 'Answer 2:1', 'Answer 2:2', 'Answer 2:3', 'Answer 2:4', 'Answer 2:5', ), ); foreach($quest as &$_quest) { $q = array_shift($_quest); shuffle($_quest); array_unshift($_quest, $q); } print_r($quest); ?></pre> PHP: