2
\$\begingroup\$

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 => $value) {
            $tmp[] = array('key' => $key, 'value' => $value);
        }
        $arr = $tmp;
    }
    for($x = 1; $x <= $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!

\$\endgroup\$
1
\$\begingroup\$

This function shouldn't be.

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.

\$\endgroup\$
  • \$\begingroup\$ Seriously. I told you already: write a function only when you face a real life task for which there is no good solution yet. But with functions you wrote just in case, you will just bloat your helper. \$\endgroup\$ – Your Common Sense Oct 31 '17 at 15:43
  • 1
    \$\begingroup\$ I wasn't going to add this to my helper unless I could think of actually useful situations. I was just bored and I like programming functions. I like learning new ways of doing things. \$\endgroup\$ – GrumpyCrouton Oct 31 '17 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.