How to generate random Hex color in PHP
PHP

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.

Get The latest Coding solutions.

Subscribe to the Email Newsletter