PHP

Randomly Shuffle the Order of a PHP Array

Discover how to effectively randomize the order of elements within a PHP array using the `shuffle()` function, ideal for card games, quizzes, or presenting varied content.

<?php
$deckOfCards = [
    'Ace of Spades', 'King of Hearts', 'Queen of Diamonds', 'Jack of Clubs',
    'Ten of Spades', 'Nine of Hearts', 'Eight of Diamonds', 'Seven of Clubs'
];

// Shuffle the array
shuffle($deckOfCards);
// $deckOfCards now contains the same elements but in a random order
// Example: ['Queen of Diamonds', 'Ace of Spades', 'Seven of Clubs', ...]

echo "Shuffled Deck (first run): " . json_encode($deckOfCards) . "
";

// Shuffle again for a different order
shuffle($deckOfCards);
echo "Shuffled Deck (second run): " . json_encode($deckOfCards) . "
";

$quizQuestions = [
    ['question' => 'What is 2+2?', 'answer' => 4],
    ['question' => 'Capital of France?', 'answer' => 'Paris'],
    ['question' => 'First element on the periodic table?', 'answer' => 'Hydrogen']
];

// Shuffle an array of associative arrays (often used for quizzes, etc.)
shuffle($quizQuestions);
echo "Shuffled Quiz Questions: " . json_encode($quizQuestions) . "
";
?>
How it works: The `shuffle()` function in PHP randomizes the order of all elements in an array. It reassigns new keys to the elements, meaning any existing string keys will be removed, and numeric keys will be re-indexed starting from 0. This function is useful for scenarios requiring unpredictable order, such as shuffling a deck of cards, randomizing quiz questions, or displaying testimonials in a varied sequence.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs