PHP
Randomly Shuffle All Elements in a PHP Array
Learn how to randomize the order of all elements within a PHP array using `shuffle()`, useful for displaying items in a non-sequential manner like card decks or quizzes.
<?php
$cards = ['Ace', 'King', 'Queen', 'Jack', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
echo "Original Cards: " . implode(', ', $cards) . "
";
// Shuffle the array
shuffle($cards);
echo "Shuffled Cards 1: " . implode(', ', $cards) . "
";
// Shuffle again for a different order
shuffle($cards);
echo "Shuffled Cards 2: " . implode(', ', $cards) . "
";
$quizQuestions = [
'What is the capital of France?',
'Which planet is known as the Red Planet?',
'Who painted the Mona Lisa?',
'What is the chemical symbol for water?'
];
echo "Original Quiz Order:
";
foreach ($quizQuestions as $index => $question) {
echo ($index + 1) . ". " . $question . "
";
}
shuffle($quizQuestions);
echo "
Shuffled Quiz Order:
";
foreach ($quizQuestions as $index => $question) {
echo ($index + 1) . ". " . $question . "
";
}
?>
How it works: The `shuffle()` function in PHP randomly reorders all elements in an array. It directly modifies the input array and does not return a new one. This is particularly useful for scenarios where you need to present a list of items in an unpredictable sequence, such as drawing cards, randomizing quiz questions, or creating dynamic carousels. Note that keys are removed and elements are re-indexed numerically after shuffling.