开发者

php get two different random array elements [duplicate]

This question already has answers here: How do I select 10 random things from a list in PHP? (5 answers) Closed 5 months ago.

From an array

 $my_array = array('a','b','c','d','e');

I want to get two DIFFERENT random elements.

With the following code:

 for ($i=0; $i<2; $i++) {
    $random = array_rand($my_array);  # one random array element number
    $get_it = $my_array[$random];    # get the letter from the array
    echo $get_it;
 }

it is possible开发者_如何学C to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that? Thanks


array_rand() can take two parameters, the array and the number of (different) elements you want to pick.

mixed array_rand ( array $input [, int $num_req = 1 ] )
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
  echo $my_array[$key];
}


What about this?

$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.


You could always remove the element that you selected the first time round, then you wouldn't pick it again. If you don't want to modify the array create a copy.

 for ($i=0; $i<2; $i++) {
    $random = array_rand($my_array);  # one random array element number
    $get_it = $my_array[$random];    # get the letter from the array
    echo $get_it;

    unset($my_array[$random]);
 }


foreach (array_intersect_key($arr, array_flip(array_rand($arr, 2))) as $k => $v) {
    echo "$k:$v\n";
}

//or

list($a, $b) = array_values(array_intersect_key($arr, array_flip(array_rand($arr, 2))));


You can shuffle and then pick a slice of two. Use another variable if you want to keep the original array intact.

$your_array=[1,2,3,4,5,6,7];
shuffle($your_array); // randomize the order
$your_array = array_slice($your_array, 0, 2); //pick 2


here's a simple function I use for pulling multiple random elements from an array.

function get_random_elements( $array, $limit=0 ){

    shuffle($array);

    if ( $limit > 0 ) {
        $array = array_splice($array, 0, $limit);
    }

    return $array;
}


Here's how I did it. Hopefully this helps anyone confused.

$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
  echo $newArray[$i];
}


Get the first random, then use a do..while loop to get the second:

$random1 = array_rand($my_array);
do {
    $random2 = array_rand($my_array);
} while($random1 == $random2);

This will keep looping until random2 is not the same as random1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜