Last Updated: February 25, 2016
·
1.869K
· citizenk

Random output from an array in PHP

Let's say you want to output a value between string0 and string7, at random, with PHP:

<?php
    $randomString = array(
    "string0",
    "string1",
    "string2",
    "string3",
    "string4",
    "string5",
    "string6",
    "string7"
    );
    print_r($randomString [array_rand($randomString )]);
?>

One point you should be aware of is that, if you leave array_rand empty, it will return the array key, not its value. Hence the repetition of $randomString...

Gist: http://gist.github.com/3159622

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside