get a sample of 5 elements from an array in php

To get a random sample of 5 elements from an array in PHP, you can use the array_rand function along with a loop to create a new array with the selected elements. Here's an example:

main.php
$array = array('apple', 'orange', 'banana', 'pear', 'grape', 'kiwi', 'pineapple');

$sample = array();
$keys = array_rand($array, 5);
foreach ($keys as $key) {
    $sample[] = $array[$key];
}

print_r($sample);
211 chars
10 lines

In this example, we start with an array of fruits. We create an empty array called $sample to hold the selected elements. We then use array_rand to select 5 random keys from the $array, which will give us 5 random indices. We use a loop to iterate through these keys, and for each one we append the corresponding element from $array to $sample. Finally, we print out the resulting $sample array using print_r.

Note that the elements will be selected randomly, so the output may vary each time you run the script. Also, if the original array contains fewer than 5 elements, the code above will produce a "Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array" warning.

gistlibby LogSnag