php get random value from array code example

Example 1: choose a random word from an array php

$items = array(1, 2, 3, 4, 5);
echo $items[array_rand($items)];

Example 2: php get random element from array

<?php
//array_rand ( array $array [, int $num = 1 ] ) 
$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";
?>

Example 3: php get random value from array

$colors=["red","blue","green","orange"];
echo $colors[array_rand($colors)];//green (or any color randomly)

Tags:

Php Example