0

I am currently using the code found on PHP quiz with on screen results which is grade.php:

<?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'
    )
);

if (isset($_POST['answers'])){
    $Answers = $_POST['answers']; // Get submitted answers.

    // Now this is fun, automated question checking! ;)

    foreach ($Questions as $QuestionNo => $Value){
        // Echo the question
        echo $Value['Question'].'<br />';

        if ($Answers[$QuestionNo] != $Value['CorrectAnswer']){
             echo 'You answered: <span style="color: red;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span><br>'; // Replace style with a class
             echo 'Correct answer: <span style="color: green;">'.$Value['Answers'][$Value['CorrectAnswer']].'</span>';
        } else {
            echo 'Correct answer: <span style="color: green;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span><br>'; // Replace style with a class
            echo 'You are correct: <span style="color: green;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span>'; $counter++;

        }

        echo '<br /><hr>'; 
                                if ($counter=="") 
                                { 
                                $counter='0';
                                $results = "Your score: $counter/2"; 
                                }
                                else 
                                { 
                                $results = "Your score: $counter/2"; 
                                }
            }                           echo $results;
} else {  
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="quiz">
    <?php foreach ($Questions as $QuestionNo => $Value){ ?>

        <h3><?php echo $Value['Question']; ?></h3>
        <?php 
            foreach ($Value['Answers'] as $Letter => $Answer){ 
            $Label = 'question-'.$QuestionNo.'-answers-'.$Letter;
        ?>
        <div>
            <input type="radio" name="answers[<?php echo $QuestionNo; ?>]" id="<?php echo $Label; ?>" value="<?php echo $Letter; ?>" />
            <label for="<?php echo $Label; ?>"><?php echo $Letter; ?>) <?php echo $Answer; ?> </label>
        </div>
        <?php } ?>

    <?php } ?>
    <input type="submit" value="Submit Quiz" />
    </form>
<?php 
}
?>

The code works fine but I was wondering how am I able to display the questions randomly(To show 1 out of the 2 questions randomly)? I have tried array_rand(); but I am not able to implement that into these codes. Would appreciate any help I could get, thank you in advance!

Shane
  • 3
  • 1
  • create a function to return a random int. Use that int in $questions[$returnedValue] etc. - also is much better to have camelCase or under_score than capitlise first letter personally pref. camelCase but using capitlised first letter adds an extra key stroke per value – treyBake Feb 11 '19 at 09:35

5 Answers5

0

I hope I have understand your requirement correctly. Please check below code if it helps:

<?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'
    )
);

if (isset($_POST['answers'])){
    $Answers = $_POST['answers']; // Get submitted answers.

    // Now this is fun, automated question checking! ;)

    foreach ($Questions as $QuestionNo => $Value){
        // Echo the question
        echo $Value['Question'].'<br />';

        if ($Answers[$QuestionNo] != $Value['CorrectAnswer']){
             echo 'You answered: <span style="color: red;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span><br>'; // Replace style with a class
             echo 'Correct answer: <span style="color: green;">'.$Value['Answers'][$Value['CorrectAnswer']].'</span>';
        } else {
            echo 'Correct answer: <span style="color: green;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span><br>'; // Replace style with a class
            echo 'You are correct: <span style="color: green;">'.$Value['Answers'][$Answers[$QuestionNo]].'</span>'; $counter++;

        }

        echo '<br /><hr>'; 
                                if ($counter=="") 
                                { 
                                $counter='0';
                                $results = "Your score: $counter/2"; 
                                }
                                else 
                                { 
                                $results = "Your score: $counter/2"; 
                                }
            }                           echo $results;
} else {  
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="quiz">
    <?php 
    $totalQuestionCount = count($Questions);
    $randQuestions = rand(0, ($totalQuestionCount - 1));
    shuffle($Questions);
    foreach ($Questions as $QuestionNo => $Value) {

        ?>

        <h3><?php echo $Value['Question']; ?></h3>
        <?php 
            foreach ($Value['Answers'] as $Letter => $Answer){ 
            $Label = 'question-'.$QuestionNo.'-answers-'.$Letter;
        ?>
        <div>
            <input type="radio" name="answers[<?php echo $QuestionNo; ?>]" id="<?php echo $Label; ?>" value="<?php echo $Letter; ?>" />
            <label for="<?php echo $Label; ?>"><?php echo $Letter; ?>) <?php echo $Answer; ?> </label>
        </div>
        <?php } 

        if ($QuestionNo == $randQuestions) {
            break;
        }
        ?>
    <?php } ?>
    <input type="submit" value="Submit Quiz" />
    </form>
<?php 
}
?>

You can further update it according to your requirement.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18
  • Hey Rohit, thank you so much for your reply. Your code successfully helps to shuffle the question, but how can I go around displaying 10 questions if I have a total of 20? – Shane Feb 11 '19 at 10:04
  • You can use PHP chunk function for this on array. check this link: https://www.w3schools.com/php/showphp.asp?filename=demo_func_array_chunk – Rohit Mittal Feb 11 '19 at 10:16
0

You can do something like

$questionToDisplay = $Questions[array_rand($Questions)];

You said that array_rand can not be implemented. In that case you can get a random integer as an index:

$questionToDisplay = $Questions[mt_rand(1, count($Questions))];

In both examples, I've extracted one random question into $questionToDisplay variable.

Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27
0

You can use shuffle($Questions) to randomise an array.

In example :

$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 the answer to life the universe and everything',
        'Answers' => array(
            'A' => 'What???',
            'B' => '42',
            'C' => 'I should read The Hitchhiker\'s Guide to the Galaxy'
        ),
        'CorrectAnswer' => 'B'
    ),
    4 => array(
        'Question' => '4. What is your name',
        'Answers' => array(
            'A' => 'Sir Galahad of Camelot',
            'B' => 'Sir Robin of Camelot',
            'C' => 'Sir Launcelot of Camelot'
        ),
        'CorrectAnswer' => 'C'
    ),
    5 => array(
        'Question' => '5. What is your quest',
        'Answers' => array(
            'A' => 'To seek a shrubbery',
            'B' => 'To seek the Holy Grail',
            'C' => 'To seek a coconut'
        ),
        'CorrectAnswer' => 'B'
    ),
    6 => array(
        'Question' => '6. What is your favorite color',
        'Answers' => array(
            'A' => 'What do you mean? An African or European swallow?',
            'B' => 'Blue.',
            'C' => 'Blue. No yel-- Auuuuuuuugh!'
        ),
        'CorrectAnswer' => 'B'
    )
);

shuffle($Questions);

var_dump($Questions);

Output

array (size=6)
  0 => 
    array (size=3)
      'Question' => string '5. What is your quest' (length=21)
      'Answers' => 
        array (size=2)
          'A' => string 'To seek a coconut' (length=17)
          'B' => string 'To seek the Holy Grail' (length=22)
      'CorrectAnswer' => string 'B' (length=1)
  1 => 
    array (size=3)
      'Question' => string '6. What is your favorite color' (length=30)
      'Answers' => 
        array (size=3)
          'A' => string 'What do you mean? An African or European swallow?' (length=49)
          'B' => string 'Blue.' (length=5)
          'C' => string 'Blue. No yel-- Auuuuuuuugh!' (length=27)
      'CorrectAnswer' => string 'B' (length=1)
  2 => 
    array (size=3)
      'Question' => string '1. CSS stands for' (length=17)
      'Answers' => 
        array (size=3)
          'A' => string 'Computer Styled Sections' (length=24)
          'B' => string 'Cascading Style Sheets' (length=22)
          'C' => string 'Crazy Solid Shapes' (length=18)
      'CorrectAnswer' => string 'B' (length=1)
  3 => 
    array (size=3)
      'Question' => string '4. What is your name' (length=20)
      'Answers' => 
        array (size=3)
          'A' => string 'Sir Galahad of Camelot' (length=22)
          'B' => string 'Sir Robin of Camelot' (length=20)
          'C' => string 'Sir Launcelot of Camelot' (length=24)
      'CorrectAnswer' => string 'C' (length=1)
  4 => 
    array (size=3)
      'Question' => string '3. What is the answer to life the universe and everything' (length=57)
      'Answers' => 
        array (size=3)
          'A' => string 'What???' (length=7)
          'B' => string '42' (length=2)
          'C' => string 'I should read The Hitchhiker's Guide to the Galaxy' (length=50)
      'CorrectAnswer' => string 'B' (length=1)
  5 => 
    array (size=3)
      'Question' => string '2. What is the Capital of the Philippines' (length=41)
      'Answers' => 
        array (size=3)
          'A' => string 'Cebu City' (length=9)
          'B' => string 'Davao City' (length=10)
          'C' => string 'Manila City' (length=11)
      'CorrectAnswer' => string 'C' (length=1)
Cid
  • 14,968
  • 4
  • 30
  • 45
0

Before you call foreach() on your form you should random that's array .

use array_rand() and if you have more than 5 array then you get the difference of random

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="quiz">
   <?php 
   $questionRandom = array_rand($a,count($Questions));
   foreach ($Questions as $QuestionNo => $Value){ 
   ?>

    <h3><?php echo $Value['Question']; ?></h3>
    <?php 
        foreach ($Value['Answers'] as $Letter => $Answer){ 
        $Label = 'question-'.$QuestionNo.'-answers-'.$Letter;
    ?>
    <div>
        <input type="radio" name="answers[<?php echo $QuestionNo; ?>]" id="<?php echo $Label; ?>" value="<?php echo $Letter; ?>" />
        <label for="<?php echo $Label; ?>"><?php echo $Letter; ?>) <?php echo $Answer; ?> </label>
    </div>
    <?php } ?>

<?php } ?>
<input type="submit" value="Submit Quiz" />
</form>
MD. Jubair Mizan
  • 1,539
  • 1
  • 12
  • 20
0

you can set it up like this one

$qrand = rand(1,2);
foreach($Questions as $QuestionNo => $Value){
  if($qrand == $Value['Question']){
  //display question
  } else {
  //do nothing 
  }
}
Vic Zapico
  • 24
  • 2