DolDurma
DolDurma

Reputation: 17279

generate random set of values from array

i want to get static length to get any random value from array.

PHP CODE:

in this below code how to get 5 random value from array?

$arr_history = array(23, 44,24,1,345,24,345,34,4,35,325,34,45,6457,57,12);
$lenght=5;
for ( $i = 1; $i < $lenght; $i++ )
     echo array_rand($arr_history);

Upvotes: 1

Views: 247

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173522

You can use array_rand() to pick 5 random keys and then use those to intersect with the array keys; this keeps the original array intact.

$values = array_intersect_key($arr_history, array_flip(array_rand($arr_history, 5)));

Demo

Alternatively, you can first shuffle the array in-place and then take the first or last 5 entries out:

shuffle($arr_history);
$values = array_slice($arr_history, -5);

This has the advantage that you can take multiple sets out consecutively without overlaps.

Upvotes: 2

Prasanth Bendra
Prasanth Bendra

Reputation: 32710

Try this :

$rand_value = array_rand($arr_history);

echo $rand_value;

REF: http://php.net/manual/en/function.array-rand.php

OR use :

shuffle($arr_history)

This will shuffle the order of the array : http://php.net/manual/en/function.shuffle.php

Upvotes: 0

Related Questions