Asked  7 Months ago    Answers:  5   Viewed   40 times

I have an array called $ran = array(1,2,3,4);

I need to get a random value out of this array and store it in a variable, how can I do this?

 Answers

41

You can also do just:

$k = array_rand($array);
$v = $array[$k];

This is the way to do it when you have an associative array.

Wednesday, March 31, 2021
 
Gilko
answered 7 Months ago
45

The following is part of the List interface (which ArrayList implements):

E e = list.get(list.size() - 1);

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException. You can find the whole API documentation here.

Tuesday, June 1, 2021
 
diegoiglesias
answered 5 Months ago
25

like this

alert(ary[0])
Wednesday, June 2, 2021
 
hakre
answered 5 Months ago
83

You can use array_multisort to order the array values by a second array of mt_rand values:

$arr = array(1,2,3,4,5,6);

mt_srand('123');
$order = array_map(create_function('$val', 'return mt_rand();'), range(1, count($arr)));
array_multisort($order, $arr);

var_dump($arr);

Here $order is an array of mt_rand values of the same length as $arr. array_multisort sorts the values of $order and orders the elements of $arr according to the order of the values of $order.

Friday, July 16, 2021
 
Rocket
answered 4 Months ago
59

I think something like this will do what you want:

sample

(click the submit button multiple times on the sample to get the code to re-execute)

$fruits = array('apple' => '20', 'orange' => '40', 'pear' => '40');

$newFruits = array();
foreach ($fruits as $fruit=>$value)
{
    $newFruits = array_merge($newFruits, array_fill(0, $value, $fruit));
}

$myFruit = $newFruits[array_rand($newFruits)];

This creates an array ($newFruits), which is a numerically-indexed array with 100 elements. 20 of those elements are 'apple', 40 are 'orange', and 40 are 'pear'. Then we select a random index from that array. 20 times out of 100 you will get 'apple', 40 times out of 100 you will get 'orange', and 40 times out of 100 you will get 'pear'.

Friday, July 30, 2021
 
PedroKTFC
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :