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?



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
answered 7 Months ago

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
answered 5 Months ago

like this

Wednesday, June 2, 2021
answered 5 Months ago

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

$order = array_map(create_function('$val', 'return mt_rand();'), range(1, count($arr)));
array_multisort($order, $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
answered 4 Months ago

I think something like this will do what you want:


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