PHP: Random unique array value (using an Inline anonymous function)

Published on Author Yani1 Comment

Here’s a small piece of code I wrote which plays around with inline anonymous functions.

It shows you a unique value of an array, even when refreshing the page. The output will be different every time and no value will ever be shown twice in a row.

 

@session_start();

$terms = ['ayo', 'test', 'yani'];

echo $terms[call_user_func(
    function($terms, $num){
        do $_SESSION['poem'] = mt_rand(0, count($terms) - 1);
            while($num == $_SESSION['poem']);
        return $_SESSION['poem'];
    },
    $terms,
    $num = (
        isset($_SESSION['poem'])) ?
        $_SESSION['poem'] :
        mt_rand(0, count($terms) - 1
    )
)];

 

I think it shows really good how inline anonymous functions can be used for some amazing things.

 

Categories PHP

One Response to PHP: Random unique array value (using an Inline anonymous function)

Leave a Reply

Your email address will not be published. Required fields are marked *