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

Each item of this array is some number.

How do I get random item from $items?

James
  • 42,081
  • 53
  • 136
  • 161

4 Answers4

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

array_rand()

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
  • 5
    Used this inline to randomly pick youtube video from playlist on page load and is working great: – ioTus Jul 03 '14 at 06:07
  • 66
    @TimoHuovinen also there might be an alien standing behind you... It doesn't concern the question directly. – sitilge Aug 07 '15 at 09:07
  • Remember to seed this function with ´srand()´ because of a known bug in PHP that does not seed it automatically. – Sanxofon Apr 18 '21 at 00:43
42

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

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

Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
pastapockets
  • 1,088
  • 2
  • 13
  • 20
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

Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
  • 2
    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); – Gregory Bowers Jun 30 '20 at 17:33
  • @GregoryBowers the shuffle function is suppose to return a boolean. so your code won't work. – MusheAbdulHakim Jul 15 '23 at 12:06
  • Yes, you are right, but this DOES. – Gregory Bowers Jul 18 '23 at 01:00
  • 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. – Gregory Bowers Jul 18 '23 at 01:08
10

use array_rand()

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

Christophe
  • 4,798
  • 5
  • 41
  • 83