254
$items = Array(523,3452,334,31,...5346);

Each item of this array is some number.

How do I get random item from $items?

1

4 Answers 4

591
echo $items[array_rand($items)];

array_rand()

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

3 Comments

Used this inline to randomly pick youtube video from playlist on page load and is working great: <?php $videos = Array(0,1,2,3); echo $videos[array_rand($videos)]; ?>
@TimoHuovinen also there might be an alien standing behind you... It doesn't concern the question directly.
Remember to seed this function with ´srand()´ because of a known bug in PHP that does not seed it automatically.
44

If you don't mind picking the same item again at some other time:

$items[rand(0, count($items) - 1)];

3 Comments

How would you go about getting a random item when the keys are not numeric?
…or if they keys are not in order (e.g., if you have unset array elements).
1. this will work if array comes from explode so keys are numeric 2. can be seeded with mt_srand($num);
17

Use PHP Rand function

<?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";
?>

More Help

4 Comments

Yall are making this more complicated than it has to be... How about this... $to_shuffle = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); $shuffled = shuffle($to_shuffle); $shuffled = $shuffled[0]; print_r($shuffled);
@GregoryBowers the shuffle function is suppose to return a boolean. so your code won't work.
<?php $to_shuffle = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); shuffle($to_shuffle); print_r($to_shuffle); ?> Yes, you are right, but this DOES.
Don't declare $shuffled, shuffle($array) will apply to the original array. $to_shuffle will return a new shuffled array. So you are correct. This does work though. <?php $to_shuffle = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); shuffle($to_shuffle); print_r($to_shuffle); ?>
10

use array_rand()

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.