0

I need to be able to pull a random value out of my array, let's assume i have array with 100 values, how can i pull randomly 5 values out of this array?

1
  • Might want to check this out if the quality of the pseudo-randomness is important: cod.ifies.com/2008/05/…. Commented Sep 30, 2009 at 23:25

5 Answers 5

5

Try this:

$data = range(1, 100);

$results = array_rand($data, 5);
print_r($results);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that in PHP 5.2.10 and up this no longer works. You need to add shuffle to get randomness.
3

with array_rand(), produced array will always be ordered

$results[0] < $results[1] < $results[2] < $results[3] < $results[4]

if you want it to be unordered, after array_rand(), you can use shuffle() function

$data = range(1, 100);
$results = array_rand($data, 5);
shuffle($result);
print_r($results);

Comments

1

You are correct.

according to https://www.php.net/manual/en/function.array-rand.php

you can do:

<?php
 $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
 $rand_keys = array_rand($input, 2);
 echo $input[$rand_keys[0]] . "\n";
 echo $input[$rand_keys[1]] . "\n";
?>



  

Comments

0

actually I just found array_rand(); maybe that?

Comments

-1

can this be done with repeating the echo or print command ( echo $input[$rand_keys[0]] . "\n"; )

1 Comment

This doesn't talk about the user's own array but instead a random function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.