[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);

// src/Controller/Snippet/Snippet42Trait.php

namespace App\Controller\Snippet;

 * I am using a PHP trait in order 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  More on Stackoverflow

» Comments

Privacy-focused with Commento. (Comment system added on 2019-11-22: be the first! πŸ₯‡)