PHP Random selection of several non-repeating elements from an array _php tutorial

Source: Internet
Author: User

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 ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.