首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 生成隨機十六進位顏色代碼:一行代碼與進階封裝

     編輯:PHP 綜合知識

最簡實現(單行)

<?php
$color = '#' . substr(md5(mt_rand()), 0, 6); // 例:#a3f2e1

原理:mt_rand() 產生隨機整數 → md5() 產生 32 位十六進位字串 → 取前 6 位。

原文遞迴版本(可讀性較好)

<?php
function randrgb(): string
{
    $hex = '0123456789ABCDEF';
    $color = '#';
    for ($i = 0; $i < 6; $i++) {
        $color .= $hex[mt_rand(0, 15)];
    }
    return $color;
}

進階封裝:支援格式、透明度、陣列輸出

<?php
/**
 * 產生隨機顏色
 * @param string $format 'hex' | 'rgb' | 'rgba' | 'array'
 * @param int|null $alpha 0-255(rgba 模式有效)
 * @return string|array
 */
function randomColor(string $format = 'hex', ?int $alpha = null)
{
    $r = mt_rand(0, 255);
    $g = mt_rand(0, 255);
    $b = mt_rand(0, 255);

    return match ($format) {
        'hex'   => sprintf('#%02X%02X%02X', $r, $g, $b),
        'rgb'   => "rgb($r, $g, $b)",
        'rgba'  => "rgba($r, $g, $b, " . ($alpha ?? mt_rand(0, 255)) / 255 . ")",
        'array' => ['r' => $r, 'g' => $g, 'b' => $b, 'a' => $alpha ?? 255],
        default => throw new InvalidArgumentException("Unsupported format: $format"),
    };
}

// 使用範例
echo randomColor();           // #3F8A2B
echo randomColor('rgb');      // rgb(120, 45, 200)
echo randomColor('rgba', 128); // rgba(30, 180, 90, 0.502)
print_r(randomColor('array')); // Array ( [r] => 100 [g] => 50 [b] => 200 [a] => 255 )

應用場景範例

1. 圖表資料集自動配色

<?php
$datasets = [];
foreach ($categories as $cat) {
    $datasets[] = [
        'label' => $cat,
        'backgroundColor' => randomColor('rgba', 100),
        'borderColor' => randomColor('hex'),
        'data' => $catData[$cat],
    ];
}

2. CSS 變數動態生成

<?php
$colors = [];
for ($i = 1; $i <= 10; $i++) {
    $colors[] = "--color-$i: " . randomColor('hex') . ";";
}
$cssVars = implode("\n", $colors);
// 輸出到