Monday, November 18, 2013

Random values from an Array using php

Below is the function to pick random values from an existing array

function array_pick_random($arr, $number = 1) {
    shuffle($arr);
   
    $r = array();
    for ($i = 0; $i < $number; $i++) {
        $r[] = $arr[$i];
    }
    return $number == 1 ? $r[0] : $r;
}

In the above function '$arr' is the Array which we want to get the random values.

'$number' is the number of array elements need to return.

Function returns an array if '$number' contains more than 1.