Skip to content

Instantly share code, notes, and snippets.

@agarzon
Last active August 15, 2024 13:29
Show Gist options
  • Save agarzon/2322495 to your computer and use it in GitHub Desktop.
Save agarzon/2322495 to your computer and use it in GitHub Desktop.
PHP Random Color Generator Hex
<?php $color = dechex(rand(0x000000, 0xFFFFFF)); ?>
<body style="background-color: <?php echo $color; ?>;">
<h1><?php echo $color ?></h1>
</body>
@Slinjez
Copy link

Slinjez commented Jan 25, 2017

you can then add it to make a string with
$stringMyColor="#".$newColor;

@MmdRza-Eslami
Copy link

<?php

function ClrGen1($Red = ['00', 'ff'], $Green = ['00', 'ff'], $Blue = ['00', 'ff'])
{
	$tmp = mt_rand(hexdec($Red[0]), hexdec($Red[1]));
	$Red = strlen($tmp < 10) ? '0' . dechex($tmp) : dechex($tmp);

	$tmp = mt_rand(hexdec($Green[0]), hexdec($Green[1]));
	$Green = strlen($tmp < 10) ? '0' . dechex($tmp) : dechex($tmp);

	$tmp = mt_rand(hexdec($Blue[0]), hexdec($Blue[1]));
	$Blue = strlen($tmp < 10) ? '0' . dechex($tmp) : dechex($tmp);

	return '#' . $Red . $Green . $Blue;
}

function ClrGen2($Red = [0, 255], $Green = [0, 255], $Blue = [0, 255])
{
	$tmp = mt_rand($Red[0], $Red[1]);
	$Red = strlen($tmp < 10) ? '0' . dechex($tmp) : dechex($tmp);

	$tmp = mt_rand($Green[0], $Green[1]);
	$Green = strlen($tmp < 10) ? '0' . dechex($tmp) : dechex($tmp);

	$tmp = mt_rand($Blue[0], $Blue[1]);
	$Blue = strlen($tmp < 10) ? '0' . dechex($tmp) : dechex($tmp);

	return '#' . $Red . $Green . $Blue;
}

$hex = ClrGen1();
$rgb = ClrGen2();

?>

<h1 style="background-color: <?php echo($hex); ?>;"><?php echo($hex); ?></h1>

<h1 style="background-color: <?php echo($rgb); ?>;"><?php echo($rgb); ?></h1>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment