How to shuffle an array of objects in PHP

Summary:

You should create a custom function that utilizes the rand() and shuffle() if you want to shuffle an array of objects in PHP. This way you can get random items within a child object.

Shuffle array in PHP

PHP shuffle function shuffle array in PHP. The article uses this function to build a minimalistic console-based game, “The Quiz Game”.

Introduction

PHP arrays are flexible in terms of the elements datatypes. Arrays can have mixed types, including objects. The element’s index denotes its position in an array, where the leftmost element has an index of zero. One cool thing is random shuffling in an array. Randomized shuffling is super important if you’re trying to develop a game of chance, for instance, Poker.

shuffle array in PHP

This article includes an array of objects. These objects are instances of a class Quiz. The class represents a typical quiz question with multiple answers. This article demonstrates how to shuffle array in PHP and builds a console-based program that displays random quiz questions. So let’s start without further ado.

The Quiz Class

Here’s the “Quiz” class. The array will hold the instances of this class.

class Quiz {
    private $questionText;
    private $answersArray;
 
    function __construct($questionText, $answersArray) {
        $this->questionText = $questionText;
        $this->answersArray = $answersArray;
    }
 
    function getQuestion() {
        return $this->questionText;
    }
 
    function getAnswersArray() {
        return $this->getAnswersArray;
    }
 
    function setQuestion($questionText) {
        $this->questionText = $questionText;
    }
   
    function setAnswersArray($answersArray) {
        $this->answersArray = $answersArray;
    }
 
}

The Quiz Objects 

Here are a few instances of the “Quiz” class.

$question1 = new Quiz("What is the capital of USA?",
                      [
                          ["Washington, D.C", "Correct"],
                          ["California", "Incorrect"],
                          ["Texas", "Incorrect"]
                      ]);
 
$question2 = new Quiz("Where is the Great Wall located?",
                      [
                          ["Canada", "Incorrect"],
                          ["China", "Correct"],
                          ["India", "Incorrect"]
                      ]);
 
$question3 = new Quiz("Who was the first man on the moon?",
                     [
                        ["Joseph Swan", "Incorrect"],
                        ["Nicola Tesla", "Incorrect"],
                        ["Neil Armstrong", "Correct"]
                     ]);

Every object is initialized with a text-based question and an array having nested arrays, each with an answer and the status, “Correct” or “Incorrect”

The Quiz Game – Shuffle array in PHP

The envisioned quiz game needs to pick randomly from an array of “Quiz” objects. Fortunately, PHP features a function shuffle(). So, let’s see how that works.

PHP shuffle

shuffle(array &$array): bool

The shuffle function in PHP takes an array by reference, shuffling the elements in place. Let’s see an example.

$arr = ["First", "Second", "Third", "Fourth", "Fifth"];
print_r($arr);
 
/*
OUTPUT BEFORE SHUFFLING
Array
(
    [0] => First
    [1] => Second
    [2] => Third
    [3] => Fourth
    [4] => Fifth
)
*/

Here’s the output after shuffling.

shuffle($arr);
print_r($arr);
 
/*
OUTPUT AFTER SHUFFLING
Array
(
    [0] => Fourth
    [1] => Third
    [2] => First
    [3] => Fifth
    [4] => Second
)
*/

Voila! That’s how to shuffle array in PHP.

The Quiz Game – Shuffle array in PHP

Now that we know how to shuffle array in PHP let’s build “The Quiz Game”

Helper functions

The game needs some functions for core functionalities. Let’s check these out.

function randomize(&$quizArray) {
 
    //If array is exhausted return null.
    if(empty($quizArray)) return null;
 
    //Select a random index.
    $randomIndex = rand(0, count($quizArray) - 1);
 
    //Shuffle array.
    shuffle($quizArray);
 
 
    //Pick the question at random index.
    $question = array_splice($quizArray, $randomIndex, 1);
   
    return $question[0];
}


The randomize() function picks questions at random and passes them on to the central control.

function displayQuestion($questionCount,$question) {
 
    echo 'Quesion#'.$questionCount.': '.$question->getQuestion().PHP_EOL;
    echo 'Option1. '.$question->getAnswersArray()[0][0].PHP_EOL;
    echo 'Option2. '.$question->getAnswersArray()[1][0].PHP_EOL;
    echo 'Option3. '.$question->getAnswersArray()[2][0].PHP_EOL;
}

As the name implies, the function displayQuestion() has logic for displaying question and answer choices.

function verifyAnswer($question, $answer) {
    if(!in_array($answer, [1, 2, 3, -1])) {
        throw new Exception('Input not supported');
    }
 
    if($answer == "-1") {
        return -1;
    }
 
    foreach($question->getAnswersArray() as $k => $v) {
        //If the user picks the right answer.
        if(($answer - 1)== intval($k) && $v[1] == "Correct") {
            return 1;
        }    
    }
 
    return 0;
}

The verifyAnswer() function checks the user input and reacts accordingly.

Main Code

Here’s the main code or entry point of “The Quiz Game”.

//Array of Quiz Objects
$quizQuestions = [$question1, $question2, $question3];
 
 
echo "Welcome to the Quiz Game".PHP_EOL.PHP_EOL;
$name = readline("Please enter your name: ");
$score = 0;
$questionCount = 1;
echo "Rules\n10 Points for a correct answer\n0 Points for an incorrect answer".PHP_EOL.PHP_EOL;
 
$question = randomize($quizQuestions);
while(isset($question)) {
    displayQuestion($questionCount + 1, $question);
    $answer = readline("Enter 1, 2, 3. Press -1 to quit: ");
    $status = verifyAnswer($question,$answer);
 
    //If the answer is correct
    if($status == 1) {
        $score += 10;
        $questionCount++;
    }
 
    elseif($status == 0) {
        $score -=5;
        $questionCount++;
    }
 
    elseif($status == -1) {
        break;
    }
 
    $question = randomize($quizQuestions);
}
//Show Result
echo PHP_EOL.'SUMMARY';
echo $name.' attempted '.$questionCount.' questions'.PHP_EOL;
echo $name.' scored '.$score.' out of '.$questionCount*10;

Output

Here are snippets of a run, starting from the intro and the first question.

array php

Then we have more questions.

shuffle array in PHP
array PHP

Finally, here’s the summary.

shuffle array in PHP

Voila! I scored 30 out of 30. After all, I knew the answers beforehand 🙂 Now, that’s a minimalistic console-based game that uses array shuffling in PHP. There’s still alot of room for improvement, of course.  However, the objective here was to demonstrate a scenario where shuffling is useful.

Conclusion

The article shows how to shuffle array in PHP. It includes information about the PHP shuffle function and its usage. The article uses array shuffling in “The Quiz Game”, a minimalistic console-based game. The array shuffling is vital in similar scenarios, for instance, modelling a Poker game or probabilistic models. Hopefully, you’ve enjoyed the article and also the super simple “Quiz Game”. Stay tuned for more at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems