Generating a big random integer with PHP

Published on 2023-07-02 • Modified on 2023-07-02

This snippet shows how to generate a big random integer with PHP. It uses an undocumented PHP 8.2 function! Well, there is a documentation entry for the function, but it doesn't explain how it behaves and which problem it is supposed to address! What I understand, is that it generates a random integer of 19 digits digits as PHP_INT_MAX. So, the number is between 1000000000000000000 and PHP_INT_MAX. Use at your own risk! 😈



namespace App\Controller\Snippet;

 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet264Trait
    public function snippet264(): void
        $randomizer = new \Random\Randomizer(new \Random\Engine\Secure());
        $nextInt = $randomizer->nextInt();

        echo 'random int: '.$nextInt.PHP_EOL;
        echo 'digits: '.\strlen((string) $nextInt).PHP_EOL.PHP_EOL;

        echo 'PHP_INT_MAX: '.PHP_INT_MAX.PHP_EOL;
        echo 'digits: '.\strlen((string) PHP_INT_MAX);

        // That's it! 😁

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!