Use the following function if you want to print the text in a particular colour, depending on what the background colour is.
Sorting colors is the sort of thing that you never really think about until you need to do it. Sorting a bunch of items by their color is useful in a number of applications, but the simplest is just to display items to the user in a more controlled manner. As it happens sorting with colors is a much more complex topic than I originally thought and required digging into quite a bit more maths than I expected.
Incidentally, there is a whole world of color maths that I didn't know existed until I started looking into this. It was worth learning about though.
Here is a short bit of code to generate a random hexadecimal colour using PHP. Essentially you just create a random number between 0 (000000) and 10,000,000 (ffffff) and turn this into a hexadecimal number using the PHP function dechex.
The following function will reduce a hexadecimal colour string by a set value. It can take three and six digit colour values.