Picking random keys of an array with PHP

Published on 2023-09-13 • Modified on 2023-09-13

This snippet shows how to pick random keys of an array with PHP. This pickArrayKeys() is very convenient and, unlike most other randomizer functions, it doesn't have a "classic" equivalent before PHP 8.2. The second argument allows to specify the number of keys to return. If it is greater than the number of elements of the array, a ValueError is raised.



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 Snippet273Trait
    public function snippet273(): void
        $r = new \Random\Randomizer();
        $array = [
            'a' => 'a-',
            'b' => 'b-',
            'c' => 'c-',
            'd' => 'd-',
            'foo' => 'foofoo',
            'bar' => 'barbar',

        echo PHP_EOL;
        var_dump($r->pickArrayKeys($array, 2));

        // That's it! 😁

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!