Get random item from array

PhpRandom

Php Problem Overview


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

Each item of this array is some number.

How do I get random item from $items?

Php Solutions


Solution 1 - Php

echo $items[array_rand($items)];

array_rand()

Solution 2 - Php

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

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

Solution 3 - Php

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

Solution 4 - Php

use array_rand()

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamesView Question on Stackoverflow
Solution 1 - PhpVincent SavardView Answer on Stackoverflow
Solution 2 - PhppastapocketsView Answer on Stackoverflow
Solution 3 - PhpNaâmèn Mohamed AmineView Answer on Stackoverflow
Solution 4 - PhpChristopheView Answer on Stackoverflow