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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With