我是编程的初学者,所以我想看看这是否是正确的编码方式。我试图从数组中生成随机背景颜色。
如果有什么我遗失或有什么我可以做得更好,请告诉我。
<?php
$background_colors = array('#282E33', '#25373A', '#164852', '#495E67', '#FF3838');
$count = count($background_colors) - 1;
$i = rand(0, $count);
$rand_background = $background_colors[$i];
?>
<html>
<head>
</head>
<body style="background: <?php echo $rand_background; ?>;">
</body>
</html>
答案 0 :(得分:4)
这很不错。
但是,我会用array_rand()
...
$background_colors = array('#282E33', '#25373A', '#164852', '#495E67', '#FF3838');
$rand_background = $background_colors[array_rand($background_colors)];
代码更少,可读性更高。
答案 1 :(得分:3)
function GenerateRandomColor()
{
$color = '#';
$colorHexLighter = array("9","A","B","C","D","E","F" );
for($x=0; $x < 6; $x++):
$color .= $colorHexLighter[array_rand($colorHexLighter, 1)] ;
endfor;
return substr($color, 0, 7);
}
答案 2 :(得分:1)
<?php
function bgcolor(){return dechex(rand(0,10000000));}
?>
<html>
<head>
</head>
<body style="background:#<?php echo bgcolor(); ?>">
</body>
</html>