Reputation: 117
been building myself a website with a specific palette of five predefined colors, with the background-color being one of them. The CSS file is rendered using PHP, thanks to which I was able to get the following working (with placeholder colors):
<?php
$bg_colors = array('red', 'blue', 'green', 'yellow', 'orange');
$bg_rand = $bg_colors[array_rand($bg_colors)];
?>
background-color:<?=$bg_rand?>;
Now the question is there a way to call the four colors that have been left out by array_rand? Let's say the background-color turned out to be green, how could I call specifically #1, #2, #4 and #5?
The reason being that these five colors will be used throughout the website, and an arbitrary div with the same background-color as the body background is a no-go in this case. How can I achieve that?
Upvotes: 0
Views: 116
Reputation: 9700
You could use array_splice() to get a random one. Then the array would only have the remaining colors
array_splice($bg_colors, $random_number, 1);
Edit: typo
Upvotes: 0
Reputation: 359
You could either remove a color after using it
$rand_index = array_rand($bg_colors);
$bg_rand = $bg_colors[$rand_index];
unset($bg_colors[$rand_index]);
Or save used colors in a 2nd array called $used_colors
and then filter them out before selecting a random one
$available_colors = array_intersect($bg_colors, $used_colors);
$bg_rand = $available_colors[array_rand($available_colors)];
Upvotes: 0
Reputation: 1402
You could just suffle the array and get values one by one like this:
<?php
$bg_colors = array('red', 'blue', 'green', 'yellow', 'orange');
shuffle($bg_colors);
$bg_rand = array_shift($bg_colors);
Now you would have 4 colors left in array.
Also you could just make 5 color spesific css files and add one of those by random to the page. But then you would have as said only 5 different color schemas. Now that you could have 120 or something
Upvotes: 0
Reputation: 856
In theory, while this isn't the cleanest option, by a long shot, you could just shuffle the array and then use the first result, leaving the following 4 to work with as you please.
For example:
<?php
$bg_colors = array('red', 'blue', 'green', 'yellow', 'orange');
shuffle($bg_colors);
?>
background-color:<? echo $bg_colors[0]; ?>
This would leave the remaining 4 colours, randomly, in array values (1,2,3,4)
EG; $bg_colors[1], $bg_colors[2] etc.
Upvotes: 1