Generating a random color code with PHP

Published on 2024-12-15 • Modified on 2024-12-15

This snippet shows how to generate a random color code with PHP. In the previous snippet, we saw how to generate a random color code with Symfony. We can also directly use PHP. I like the Symfony version because it is readable and elegant, but the PHP version is more straightforward.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

/**
 * 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 Snippet333Trait
{
    public function snippet333(Request $request): void
    {
        $colorCode = \sprintf('#%06X', mt_rand(0, 0xFFFFFF)); // FFFFFF = 16 777 215

        echo \sprintf('Color code: %s', $colorCode);

        // 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 47/50: Generating a random color code with PHP www.strangebuzz.com/en/snippets/... #PHP #random #color #css

[image or embed]

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