5
\$\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\$
0

1 Answer 1

3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\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\$ Oct 31, 2017 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\$ Oct 31, 2017 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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