Generating a random color code with Symfony

Published on 2024-12-11 • Modified on 2024-12-11

This snippet shows how to generate a random color code with Symfony. We can use the ByteString::fromRandom() function of the String composnent with the hexadecimal alphabet


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\String\ByteString;

/**
 * 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 Snippet332Trait
{
    private const string HEX = '0123456789abcdef';

    public function snippet332(): void
    {
        $colorCode = ByteString::fromRandom(6, self::HEX)->toString();

        echo \sprintf('Color code: #%s / #%s ', $colorCode, strtoupper($colorCode)).PHP_EOL;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! πŸ˜‰

COil

[πŸ‡¬πŸ‡§] Snippet 46/50: Generating a random color code with Symfony www.strangebuzz.com/en/snippets/... #Symfony #PHP #random #color #css

[image or embed]

— COil 🐝 (@coil.ooo) 12 dΓ©cembre 2024 Γ  19:40