How to generate random Hex color in PHP

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\n", mt_rand( 0, 0xFFFFFF ));
?>

This is echo the color code.

 

That's it. Hope it will help you.

Tags : PHP

Related Post

How to get the php.ini file path in PHP?
Install PHP 7.4 ubuntu 20.04
How to Solve PHP Fatal error: Allowed memory size of 8388608 bytes exhausted
How to increase maximum execution time in PHP
Maksud

Maksud

I am a thinker, not a talker.