Written by Sean Behan on Fri Nov 10th 2017

Use this snippet for grabbing a random item from an array in php

    $fruits = ['apple', 'banana', 'carrot', 'date', 'elderberry'];
    echo array_rand(array_flip($fruits)); 
    // => 'banana'

PHP's array_flip makes the keys the values and the values the keys.

array_flip(['apple', 'banana', 'carrot', 'date', 'elderberry']);
=> [
 "apple" => 0,
 "banana" => 1,
 "carrot" => 2,
 "date" => 3,
 "elderberry" => 4,
    ]

You could also use shuffle but that will change the order of the original array.

shuffle($fruits);
echo $fruits[0];
// but fruits is out of order now :(
[
 "carrot",
 "apple",
 "elderberry",
 "date",
 "banana",
]

Tagged with..
#php #array #random #snippet #shuffle

Just finishing up brewing up some fresh ground comments...