Getting a random bounded integer with PHP
Published on 2023-09-07 • Modified on 2023-09-07
This snippet shows how to get a random bounded integer with PHP. This time, we use the randomizer class introduced in PHP 8.2. If you want a cryptographically secure number, use the random_int
function. Note that the parameters are included; the function can return 1 and 10 in the following example.
<?php
declare(strict_types=1);
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 Snippet270Trait
{
public function snippet270(): void
{
$r = new \Random\Randomizer();
var_dump($r->getInt(1, 10));
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc More on the web Random snippet