This article illustrates how PHP randomly selects several distinct elements from an array. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
<?php
/*
* $array = the array to is filtered
* $total = The maximum number of items to return
* $unique = Whether or not to remove duplicates before getting a random list
*/
function Unique_array ($array, $total, $unique = True) {
$newArray = Array ();
if ((bool) $unique) {
$array = Array_unique ($array);
}
Shuffle ($array);
$length = count ($array);
for ($i = 0; $i < $total; $i + +) {
if ($i < $length) {
$newArray [] = $array [$i];
}
}
return $newArray;
}
$phrases = Array (' Hello sailor ', ' Acid Test ', ' Bear Garden ', ' botch A Job ', ' Dark horse ',
' In the Red ', ' Mans up ', ' Pan out ', ' quid Pro Quo ', ' Rub It in ', ' turncoat ',
' Yes man ', ' All Wet ', ' Bag lady ', ' Bean feast ', ' Big Wig ', ' Big Wig ', ' Bear Garden '
, ' All Wet ', ' Quid Pro Quo ', ' Rub It in ');
Print_r (Unique_array ($phrases, 1));
Returns 1 Result
Print_r (Unique_array ($phrases, 5));
Returns 5 Unique Results
Print_r (Unique_array ($phrases, 5, false));
Returns 5 results, but may have duplicates if
There are duplicates in original array
Print_r (Unique_array ($phrases, 100));
Returns Unique Results
Print_r (Unique_array ($phrases, false));
Returns results, but may have duplicates if
There are duplicates in original array
I hope this article will help you with your PHP program design.