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
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 )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky π¦
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges π .
Thank you for reading! And see you soon on Strangebuzz! π
[π¬π§] Snippet 46/50: Generating a random color code with Symfony www.strangebuzz.com/en/snippets/... #Symfony #PHP #random #color #css
— COil π (@coil.ooo) 12 dΓ©cembre 2024 Γ 19:40
[image or embed]