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!