First of all I think you should take a look at this excellent blog post at Particletree.
That being said, I would use their smarty_modifier_contrast() function and modify it a little bit to address your specific needs, something like:
function color_contrast($bgcolor, $color1, $color2, $color3, ...)
{
return (hexdec($bgcolor) > 0xffffff / 2) ? min(array_slice(func_get_args(), 1)) : max(array_slice(func_get_args(), 1));
}
So you would just need to use any random color for the background (don't forget to drop the #
!) and then pass all the other colors to the array, in this case I've used a variable number of arguments but you can change it so that it accepts a single array of colors - it will then automatically pick the darkest or the lightest color depending on the $bgcolor
and provide a good enough contrast for readability:
function color_contrast($bgcolor, $colors = array())
{
return (hexdec($bgcolor) > 0xffffff / 2) ? min($colors) : max($colors);
}
To pick the $bgcolor
, you can do it randomly like I said before of use a second function to help you with this task like saturation or luminance, that really depends what you're looking for.