How PHP randomly selects several distinct elements from an array

Source: Internet
Author: User

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:

code is 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 ', ' 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.

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.