One line random value from PHP array literal

When you just want to echo one of three things in throwaway code, here’s a simple trick using PHP 5.4’s dereferencing that does it in one line.

PHP 5.4 certainly isn’t new, but a snazzy feature I use all the time in my code is array dereferencing, e.g. foo()[0] — usually without even realising, because this behaviour just makes sense. This works for more than return values though, it even works with array literals, e.g. [1, 2, 3][1] will return 2.

Rewind: Here’s where my problem began. I was creating a series of mockups that included a table, for which I wanted 5 rows with real-world-ish data. It’s throwaway, non-production code, so I just wanted to define a few options in-place and echo one at random within a loop.

What about array_rand()?

What I needed was a built-in function like echo_rand(['foo', 'bar']) that would echo the value of a random array item. But there isn’t one.

Now I know what you’re thinking: array_rand() right? Wrong. array_rand() returns a pseudo-random array key, not an item. If you want to use it with an array literal you have to define the array twice:

echo ['foo', 'bar'][array_rand(['foo', 'bar'])];

…and that’s just ridiculous.

Just use a function?!

At this point I started thinking “Sod it, I’ll write my own function and plonk it in the mockup”. It might have looked something like this:

function er($array) {
echo $array[array_rand($array)];

But that would’ve meant admitting defeat! I’d invested too much to give up now and I was determined find a workaround, if nothing else, out of spite.

Array Literati

So here it is, in all it’s glory: the culmination of an hour wasted on a petty feud with PHP core. Whack it between short echo tags for quick-win.

['foo', 'bar'][rand(0, 1)]

Note that the second param of rand() must equal number of items – 1 or you may get an error.

Here’s a useful example:

<?php for ($i = 0; $i < 5; $i++): ?>
<li><?= ['Harry', 'Ron', 'Hermione'][rand(0, 1)] ?></li>
<?php endfor; ?>

Can’t say I use this a lot, but if you’re going to waste an hour spent on a silly trick for a rare use-case you may as well spend another writing it up!

Leave a Reply

Your email address will not be published.