Skip to content
PHP Logo

How can you shuffle and display a specific number of sub-arrays in PHP?

To shuffle and display a specific number of sub-arrays in PHP, you can first shuffle the main array and then use array_chunk() function to split the array into sub-arrays of a specific size. Finally, you can display the desired number of sub-arrays using a loop.

php
// Shuffle the main array
$mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
shuffle($mainArray);

// Split the array into sub-arrays of size 3
$subArrays = array_chunk($mainArray, 3);

// Display the first 2 sub-arrays
for ($i = 0; $i < 2; $i++) {
    print_r($subArrays[$i]);
}