Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
334 views
Welcome To Ask or Share your Answers For Others

1 Answer

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...