[php-src] Issue #12734: Best Way to Random Numbers

From: Date: Mon, 20 Nov 2023 12:51:50 +0000
Subject: [php-src] Issue #12734: Best Way to Random Numbers
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-245848@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/12734
Author: celestinoxp

### Description

I normally use mt_rand(min, max) to generate random numbers to a lottery system, however, in a
"conversation" with ChatGPT I was led to a code that is supposedly more efficient, but I
would like to know your opinion on what is the best way to arrive the most random numbers...

My code (who is better mt_rand or rand_int?) :
$n1 = mt_rand(1, 45);
$n2 = mt_rand(($n1+1), 46);
$n3 = mt_rand(($n2+1), 47);
$n4 = mt_rand(($n3+1), 48);
$n5 = mt_rand(($n4+1), 49);

Code recommended by chatgpt:

$randomBytes = openssl_random_pseudo_bytes(20); // Generates 20 bytes of random data (5 numbers * 4
bytes each)
$randomIntegers = str_split($randomBytes, 4); // Divides bytes into groups of 4

$n1 = 1 + (unpack('L', $randomIntegers[0])[1] % 49);
$n2 = 1 + (unpack('L', $randomIntegers[1])[1] % 49);
$n3 = 1 + (unpack('L', $randomIntegers[2])[1] % 49);
$n4 = 1 + (unpack('L', $randomIntegers[3])[1] % 49);
$n5 = 1 + (unpack('L', $randomIntegers[4])[1] % 49);

My question is: should I use mt_rand(), rand_int(), or the code provided by chatgpt ?

### PHP Version

PHP 8.1.27

### Operating System

Windows 11


Thread (1 message)

  • celestinoxp
« previous php.bugs (#245848) next »