How to randomly extract elements from an array in php

墨辰丷
Release: 2023-03-31 19:16:01
Original
2494 people have browsed it

This article mainly introduces the method of PHP randomly selecting a number of non-repeating elements from an array. It involves common techniques related to PHP array operations. It is of great practical value. Friends who need it can refer to the example of this article.

Describes how PHP randomly selects several non-repeating elements from an array. The specific implementation method is as follows:

The code is as follows:

<?php
/*
 * $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(&#39;Hello Sailor&#39;,&#39;Acid Test&#39;,&#39;Bear Garden&#39;,&#39;Botch A Job&#39;,&#39;Dark Horse&#39;,
    &#39;In The Red&#39;,&#39;Man Up&#39;,&#39;Pan Out&#39;,&#39;Quid Pro Quo&#39;,&#39;Rub It In&#39;,&#39;Turncoat&#39;,
    &#39;Yes Man&#39;,&#39;All Wet&#39;,&#39;Bag Lady&#39;,&#39;Bean Feast&#39;,&#39;Big Wig&#39;, &#39;Big Wig&#39;,&#39;Bear Garden&#39;
    ,&#39;All Wet&#39;,&#39;Quid Pro Quo&#39;,&#39;Rub It In&#39;);
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 100 unique results    
print_r(unique_array($phrases, 100, false));
// Returns 100 results, but may have duplicates if
// there are duplicates in original array
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's learning.

Related recommendations:

How to operate MySQL database and session dialogue in php

How to match and replace callback content tags in php

PHP regular expression method to verify Email

The above is the detailed content of How to randomly extract elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template