To get a random item from a set in PHP, you can use the array_rand() function on the array representation of the set.
In this example,
mySet
containing elements.toArray
method.array_rand
function on the array to get a random key.<?php
$mySet = new Set(['Apple', 'Banana', 'Orange', 'Mango']);
$myArray = $mySet->toArray();
$randomKey = array_rand($myArray);
$randomItem = $myArray[$randomKey];
echo 'Random item from set: ' . $randomItem;
?>
Random item from set: Mango
In this tutorial, we learned How to get a Random Item in a Set in PHP language with well detailed examples.