note 119670 added to function.random-int

From: Date: Sat, 30 Jul 2016 13:11:25 +0000
Subject: note 119670 added to function.random-int
Groups: php.notes 
Request: Send a blank email to php-notes+get-206132@lists.php.net to get a copy of this message
Here is a simple backporting function, it works for PHP >= 5.1 <?php if (!function_exists('random_int')) { function random_int($min, $max) { if (!function_exists('mcrypt_create_iv')) { trigger_error( 'mcrypt must be loaded for random_int to work', E_USER_WARNING ); return null; } if (!is_int($min) || !is_int($max)) { trigger_error('$min and $max must be integer values', E_USER_NOTICE); $min = (int)$min; $max = (int)$max; } if ($min > $max) { trigger_error('$max can\'t be lesser than $min', E_USER_WARNING); return null; } $range = $counter = $max - $min; $bits = 1; while ($counter >>= 1) { ++$bits; } $bytes = (int)max(ceil($bits/8), 1); $bitmask = pow(2, $bits) - 1; if ($bitmask >= PHP_INT_MAX) { $bitmask = PHP_INT_MAX; } do { $result = hexdec( bin2hex( mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM) ) ) & $bitmask; } while ($result > $range); return $result + $min; } } ?> Randomness test <?php $max = 100; // number of random values $test = 1000000; $array = array_fill(0, $max, 0); for ($i = 0; $i < $test; ++$i) { ++$array[random_int(0, $max-1)]; } function arrayFormatResult(&$item) { global $test, $max; // try to avoid this nowdays ;) $perc = ($item/($test/$max))-1; $item .= ' '. number_format($perc, 4, '.', '') .'%'; } array_walk($array, 'arrayFormatResult'); print_r($array); ?> ---- Server IP: 72.52.91.14 Probable Submitter: 87.30.188.45 ---- Manual Page -- http://php.net/manual/en/function.random-int.php Edit -- https://master.php.net/note/edit/119670 Del: integrated -- https://master.php.net/note/delete/119670/integrated Del: useless -- https://master.php.net/note/delete/119670/useless Del: bad code -- https://master.php.net/note/delete/119670/bad+code Del: spam -- https://master.php.net/note/delete/119670/spam Del: non-english -- https://master.php.net/note/delete/119670/non-english Del: in docs -- https://master.php.net/note/delete/119670/in+docs Del: other reasons-- https://master.php.net/note/delete/119670 Reject -- https://master.php.net/note/reject/119670 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#206132) next »