PHP Code Get Random Value from Array Optional Filtered
PHP Code Function to Get a Random Value from Either Associative Array or Indexed Array and Optionally Filter the Array Prior to Grabbing Random Value
Home
Short:
/* ----------------------------------------------------------------- [1] take array $arr and optionally filter the array to remove array items that dont match $arrFilterVals. [2] randomly grab and return one of the array item and the key of the randomly grabbed item --------------------------------------------------------------- */ function randomFilteredArrVal(array $arr, array $arrFilterVals = []) { # If filter values are provided, use array_filter to filter the keys if (!empty($arrFilterVals)) { $arrKeys = array_filter(array_keys($arr), function($key) use ($arrFilterVals) { # Check if any of the filter values are present in the key foreach ($arrFilterVals as $filterVal) { if (strpos($key, $filterVal) !== false) { return true; } } return false; }); } else { # If no filter values are provided, use all the keys $arrKeys = array_keys($arr); } # Return false if no matching keys found if (empty($arrKeys)) return false; # Randomly select one of the matching keys and return the corresponding value $randomKey = $arrKeys[array_rand($arrKeys)]; return [$arr[$randomKey], $randomKey]; }
source code home