[PHP] Get a random value from an array created on the fly

Published on 2019-09-09 • Modified on 2019-09-09

This is a simple trick to get a random value of an array created on the fly. Of course, in this case, the array must have unique values. If you need real randomness, please use the random_int function.


<?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 Snippet42Trait
{
    public function snippet42(): void
    {
        echo sprintf('Random value 🎲: %s', array_rand(array_flip(['Première', 'Bac+2', 'Terminale']))); // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow  Random snippet

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet42Trait
 */
final class Snippet42Test extends KernelTestCase
{
    /**
     * @see Snippet42Trait::snippet42
     */
    public function testSnippet42(): void
    {
        $value = array_rand(array_flip(['Première', 'Bac+2', 'Terminale']));
        self::assertContains($value, ['Première', 'Bac+2', 'Terminale']);
    }
}