0

I am using the code from this grade.php. I would like to use array_Rand than using shuffle. Can anyone please help?

The code works fine but I would like to show maybe like 10 out of 20 questions instead hence using shuffle() isn't really what I wanted. Would appreciate any help I could get, thank you in advance!

Edit: I added the Array_slice and now is showing error :

Undefined index: Questions @ line 77

Igor F.
  • 2,649
  • 2
  • 31
  • 39
hellopanda
  • 61
  • 1
  • 5
  • 1
    Could you just use `array_slice` to get the first 10 shuffled questions? https://www.php.net/manual/en/function.array-slice.php – benJ Jan 27 '20 at 09:45
  • `array_rand($Questions, 10);`... – jibsteroos Jan 27 '20 at 09:47
  • @jibsteroos yes i tried but i do not know how to manipulate the foreach loop. Please advice many thanks! – hellopanda Jan 27 '20 at 09:48
  • @benJ Will i need to edit the foreach loop when echo the question and options out? As i am having trouble manipulating the code there. Please advice. Thank you – hellopanda Jan 27 '20 at 09:49
  • @benJ I tried it and i get **Undefined index: Questions at line 77 ** i have edited the code in question please check. – hellopanda Jan 27 '20 at 10:01

1 Answers1

0

You can pick Ids and then intersect the original array. Here is an example picking two at random:

<?php    
$questions = array(
    1 => array(
        'Question' => '1. CSS stands for',
        'Answers' => array(
            'A' => 'Computer Styled Sections',
            'B' => 'Cascading Style Sheets',
            'C' => 'Crazy Solid Shapes'
        ),
        'CorrectAnswer' => 'B'
    ),
    2 => array(
        'Question' => '2. What is the Capital of the Philippines',
        'Answers' => array(
            'A' => 'Cebu City',
            'B' => 'Davao City',
            'C' => 'Manila City'
        ),
        'CorrectAnswer' => 'C'
    ),
    3 => array(
        'Question' => '3. What is black and white',
        'Answers' => array(
            'A' => 'A Zebra',
            'B' => 'A Sycamore Tree',
            'C' => 'Law'
        ),
        'CorrectAnswer' => 'A'
    )
);

$rand_ids       = array_rand($questions, 2);
$rand_questions = array_intersect_key($questions, array_flip($rand_ids));
Progrock
  • 7,373
  • 1
  • 19
  • 25
  • Upon form submission get the keys from your submitted answers (that pertain to the ids here) and you can use them to intersect your questions array for the same subset. – Progrock Jan 28 '20 at 11:14