PHP

PHP: Generate Random Hex Color Code

<?php

$colors = array();
for($i = 0; $i < 10; $i++) {
	$color = $this->random_color();

	while(in_array($color, $colors)) {
		$color = $this->random_color();
	}

	$colors[] = $color;
}

foreach ($colors as $key => $value) {
	echo '<span style="color:'.$value.'"><strong>'.$value.'</strong></span><br>';
}

function random_color_part() {
		return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
    return '#'. random_color_part() . random_color_part() . random_color_part();
}

?>

Result:

random-hex-code

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × four =