1

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);
5
  • Shuffle and slice or pass 5 as second argument to array_rand. php.net/manual/en/function.array-rand.php. Commented Feb 20, 2013 at 10:19
  • 1
    shuffle($array); array_slice($array, 0, 5); //Implementation of Felix Kling's comment ;) Commented Feb 20, 2013 at 10:22
  • @FelixKling Passing 5 as 2nd argument to array_rand() returns an array of keys, not values :) Commented Feb 20, 2013 at 10:26
  • @Jack: array_rand always returns a key or keys :) And why would that be a problem? The docs say: "This is done so that you can pick random keys as well as values out of the array.". edit: I see you created a proper answer. I think I slightly misunderstood your comment, but it's all good now :) Commented Feb 20, 2013 at 10:27
  • @FelixKling You can tell I use that function on a daily basis .. ahem :) Commented Feb 20, 2013 at 10:29

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thats return static values in every refresh page
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.