2012-03-08 175 views
2

我是初学者,当谈到编程时,我想看看这是否是正确的编码方式。我试图从数组中生成随机背景颜色。阵列的随机背景颜色 - PHP

如果有什么我失踪或有什么我可以做得更好请让我知道。

<?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> 

回答

4

这很不错。

不过,我会做它像这样与array_rand() ...

$background_colors = array('#282E33', '#25373A', '#164852', '#495E67', '#FF3838'); 

$rand_background = $background_colors[array_rand($background_colors)]; 

这是更少的代码,更具可读性海事组织。

+0

啊好吧,我一直在寻找该功能,但不知道如何使用它。谢谢。 – 2012-03-08 02:32:22

1
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); 
} 
1
<?php 
    function bgcolor(){return dechex(rand(0,10000000));} 
?> 
<html> 
    <head> 
    </head> 
    <body style="background:#<?php echo bgcolor(); ?>">  

    </body> 
</html> 
+0

编辑并缩进您的代码 – HDJEMAI 2016-07-16 22:18:38

+0

@ H.Djemai谢谢 – 2016-07-17 09:51:37

+0

看起来OP希望从列表中随机选择一个项目 - 而不是任意的随机颜色。 – alex 2016-11-22 08:07:03