Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get a random array element

Short answer

array_rand() returns a random key:

<?php
 
$colors = ['red', 'green', 'blue'];
 
echo $colors[array_rand($colors)];

Several elements

Shuffle the array and take the needed number from the start:

<?php
 
$colors = ['red', 'green', 'blue', 'black'];
 
shuffle($colors);
 
echo count(array_slice($colors, 0, 2));

Output:

2

For prize draws

Where the result must not be predictable, use random_int():

<?php
 
$tickets = ['A1', 'B2', 'C3'];
 
echo $tickets[random_int(0, count($tickets) - 1)];

Functions used in this recipe

  • array_rand — Returns a random key of an array.
  • random_int — Returns a random integer from a range.
  • shuffle — Shuffles the elements of an array into a random order.

Thanks for reading!

Donate to the site — we work hard for you.