How to generate random Hex color in PHP

Avatar
C

Callum Davies

Senior Backend Engineer••
7750Views
5mRead
0Reactions

Hello,

Have a nice day. In this article, i will share simple but useful tricks with you. You can easily generate random hex color using php language. So let's start:

Tips: #1

Using rand and array, we can generate hex code.

<?php 
    
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    
?>

Then you can use $color where you want to show code.

Tips: #2

Using printf helper to generate hex color code.

<?php
echo "Hex color code: " . printf( "#%06X
", mt_rand( 0, 0xFFFFFF ));
?>

This is echo the color code.

 

That's it. Hope it will help you.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?What's your production setup for this scenario? Have you encountered similar architectural bottlenecks or edge-case gotchas?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles