3v4l.org

run code in 300+ PHP versions simultaneously
<?php class PseudoRandomSequence { const STATE_HASH = "sha512"; // 1/2 STATE_HASH block size, const STATE_SIZE = 32; private $state; public function __construct($state) { $this->state = $state; $this->mixState(); } public function int($min = 0, $max = PHP_INT_MAX) { $range = $max - $min; if ($range <= 0 || is_float($range)) { throw new Exception("Invalid min/max provided"); } $bits = 0; $tmp = $range; while ($tmp >>= 1) { $bits++; } $bytes = (int) max(ceil($bits / 8), 1); $mask = pow(2, $bits) - 1; do { $rand = $this->bytes($bytes); $result = hexdec(bin2hex($rand)) & $mask; } while ($result > $range); return $result + $min; } public function bytes($n) { $ret = ''; do { $ret .= $this->mixState(); } while (strlen($ret) < $n); return substr($ret, 0, $n); } private function mixState() { $hash = hash(self::STATE_HASH, $this->state, true); $this->state = $hash; return substr($hash, self::STATE_SIZE); } } $prng = new PseudoRandomSequence("blah"); for ($i = 0; $i < 100; $i++) { var_dump($prng->int()); }

preferences:
52.68 ms | 402 KiB | 5 Q