Asked  2 Years ago    Answers:  5   Viewed   88 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.

Tuesday, December 6, 2022

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.

Sunday, December 4, 2022

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.

Sunday, December 4, 2022

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

Tuesday, November 29, 2022

arc4random can return negative numbers which would cause you problems since negative % positive = negative A better approach would be to use arc4random_uniform

let randomIndex = arc4random_uniform(UInt32(cardArray.count))

EXC_BAD_INSTRUCTION seems like a bad exception to throw on a bounds error, but that does seem to be what you get.

Monday, September 26, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages