[PHP] Récupérer une valeur aléatoire d'un tableau créé à la volée

Publié le 09/09/2019 • Actualisé le 09/09/2019


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

C'est une astuce très simple permettant de récupérer une valeur aléatoire d'un tableau PHP créé à la volée. Bien sûr, dans ce cas, le tableau ne doit contenir que des valeurs uniques. Si vous avez besoin d'une réelle imprévisibilité, préférez utiliser la fonction random_int.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
trait Snippet42Trait
{
    public function snippet42(): void
    {
        echo sprintf('Random value 🎲: %s', array_rand(array_flip(['Première', 'Bac+2', 'Terminale']))); // That's it! 😁
    }
}

 Exécuter le snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow  Snippet aléatoire

  Travaillez avec moi !

<?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']);
    }
}