PHP randomly selects several non-repeating elements from an array
This example describes how PHP randomly selects several distinct elements from an array. Share to everyone for your reference. The implementation method is as follows:
The code is as follows:
/*
* $array = the array to be 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 ', ' Beans 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 could have duplicates if
There is duplicates in original array
Print_r (Unique_array ($phrases, 100));
Returns Unique Results
Print_r (Unique_array ($phrases, +, false));
Returns results, but could have duplicates if
There is duplicates in original array
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/969333.html www.bkjia.com true http://www.bkjia.com/PHPjc/969333.html techarticle PHP randomly selects several non-repeating elements from an array This example describes how PHP randomly selects several non-repeating elements from an array. Share to everyone for your reference. Concrete implementation ...