Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get two different random array elements

Tags:

arrays

php

random

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

like image 651
creativz Avatar asked Feb 24 '10 15:02

creativz


2 Answers

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];
}
like image 158
VolkerK Avatar answered Oct 21 '22 21:10

VolkerK


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.
like image 23
middus Avatar answered Oct 21 '22 21:10

middus