getRandom() - Randomize array and get result I've written a function that allows you to pass an array of values, which is then shuffled and returned based on a parameter $preserveArray.

This is the code:

function getRandom($arr, $preserveArray = false, $shuffles = 1) {
    if(empty($arr)) return false;
    if($preserveArray) {
        $tmp = array();
        foreach($arr as $key =&gt; $value) {
            $tmp[] = array('key' =&gt; $key, 'value' =&gt; $value);
        }
        $arr = $tmp;
    }
    for($x = 1; $x &lt;= $shuffles; $x++) {
        if(!shuffle($arr)) {
            return false;
        }
    }
    if($preserveArray) {
        $tmp = array();
        foreach($arr as $value) {
            $tmp[$value['key']] = $value['value'];
        }
        $arr = $tmp;
        return $arr;
    }
    return $arr[0];
}


So you can pass any array as the first parameter that you want randomized, then the 2nd parameter determines how the data is returned, then the 3rd parameter tells the function how many times to shuffle the array.

I've written this because I think it will be useful for people on StackOverflow, I see a lot of questions trying to figure out how to get a random value from an array.

The $preserveArray parameter tells the function to either only return a single array element if false, or return the whole array (with keys in-tact) if true.

As you can see in my code, I have to check for the 2nd parameter twice to do actions before and after the actual array shuffle. I wanted to see if anyone had any advice or knows of any ways I can improve my code.

I've been posting a lot of my code here lately, and I really enjoy how much I'm able to learn from answers. Thanks in advance!
This function shouldn't be needed.

I have a feeling that you wrote it for some imaginary people and without any particular use case in mind. And out of the false assumptions too. Neither more than one shuffle is required and you never need to shuffle an associative array. So just raw shuffle() is enough.

And you can always use $arr[array_rand($arr)]; instead of getRandom($arr); to get just a single value.