4

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 I'm 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>

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh okay, I was looking at that function but didn't know how to use it. Thank you.
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);
}

Comments

2
<?php
    function bgcolor(){return dechex(rand(0,10000000));}
?>
<html>
    <head>
    </head>
    <body style="background:#<?php echo bgcolor(); ?>">    

    </body>
</html>

1 Comment

Looks like the OP wants a random item from a list - not an arbitrary random color.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.