/**
* Generate a random color in RGB format: rgb(R, G, B)
* This program demonstrates how numbers and bits are used
* to produce valid 8‑bit channel values.
*/
/**
* Create a random 8‑bit integer (0–255).
* random_int() provides cryptographically secure randomness.
* 256 = 2^8, giving us exactly one byte of color data.
*/
function randomChannel(): int {
// 8 bits → values from 0 to 255
return random_int(0, 255);
}
/**
* Produce a random RGB color by combining the channels.
*/
function generateRandomRGB(): array {
$r = randomChannel(); // Red channel (8 bits)
$g = randomChannel(); // Green channel (8 bits)
$b = randomChannel(); // Blue channel (8 bits)
// Construct the CSS-style RGB string
$rgb = "rgb($r, $g, $b)";
return [
'r' => $r,
'g' => $g,
'b' => $b,
'rgb' => $rgb
];
}
// Run the program
$result = generateRandomRGB();
echo "Red (8 bits): {$result['r']}\n";
echo "Green (8 bits): {$result['g']}\n";
echo "Blue (8 bits): {$result['b']}\n";
echo "RGB color: {$result['rgb']}\n";
/*
run:
Red (8 bits): 107
Green (8 bits): 232
Blue (8 bits): 172
RGB color: rgb(107, 232, 172)
*/