Nick Meagher Nick Meagher - 4 months ago 15
PHP Question

Random background color from array - PHP

I am a beginner when it comes to programming so I wanted to see if this would be the right way to code this. I was trying to generate a random background color from an array. If there is something im missing or there is something I could do better please let me know.

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

Answer

That's pretty good.

However, I'd do it like so with array_rand()...

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

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

It is less code and more readable IMO.