PHP

Randomly Shuffle Elements in a PHP Array

Learn to randomly reorder the elements of a PHP array using the `shuffle()` function, useful for quizzes, lotteries, or random displays.

<?php
$cards = ['Ace', 'King', 'Queen', 'Jack', '10', '9'];

echo "Original cards: ";
print_r($cards);

shuffle($cards);

echo "Shuffled cards: ";
print_r($cards);

$items = ['item1', 'item2', 'item3', 'item4', 'item5'];

echo "Original items: ";
print_r($items);

shuffle($items);

echo "Shuffled items: ";
print_r($items);
?>
How it works: The `shuffle()` function rearranges the order of the elements in an array randomly. It modifies the array in place and does not return a new array. This is commonly used for randomization tasks such as drawing cards, selecting random quiz questions, or displaying items in a non-sequential order to users.

Need help integrating this into your project?

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

Hire DigitalCodeLabs