get a sample of 5 elements from an array without replacement in php

Here's one way to sample 5 elements from an array without replacement in PHP:

main.php
$array = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "kiwi", "lemon"];

$sample = [];

// Use array_rand() to randomly select keys from the array
$keys = array_rand($array, 5);

// Loop through the keys and add the corresponding values to the sample
foreach ($keys as $key) {
    $sample[] = $array[$key];
}

// $sample now contains 5 random elements from $array
print_r($sample);
417 chars
15 lines

This code uses the array_rand() function to randomly select 5 keys from the array without replacement. It then loops through the selected keys, adds the corresponding values to the $sample array, and prints it out.

gistlibby LogSnag