Convert Colours Between their Hexadecimal and RGB Values with PHP

The PHP functions on this page will permit you to convert hexadecimal values to their RGB value, or visa versa. Both the Hexadecimal and RGB values have very clear patters in how they’re manufactured, so they’re easy to convert – even without the built-in PHP functions.

About Hex and RGB Values

The RGB colour model is a model in which red, green, and blue light are added together in various ways to reproduce a broad array of colours. The RGB name comes from the first letter of its primary colours: Red, Blue, and Green. Each of the three values should be between 0 and 256 to create a 6-digit string (with single digit values preceded by a zero).

In math and computer science we’ll often see colours represented by a base-16 hexadecimal value ([0-9a-f]{6}). If you’re interested in learning about hex for the first time, a really sensible and visual place to start is MathIsFun … they have a little animation that visually reinforces the principles.

When you use three (hex) characters in the web world for colours it’s important that we precede each single character by the same value to form a 6-character #hexdec string (the 3-digit shorthand form reduces the palette to 4,096 colours, equivalent of 12-bit colour as opposed to 24-bit colour using the whole six-digit form, which results in 16,777,216 colours). RGB values are defined in CSS specifications and not generally honoured in all browsers – using them should be done with caution.

The PHP Functions

Convert HEX to RGB

Convert RGB to HEX

Passing the RGB values to a function presents a few potential problems because of the varied ways in which the values are represented. Using an array keeps it uniform.


We’ve got a post scheduled that’ll provide you with shortcode to represent the RGB (and other) values in various types of charts. For example, shortcode of [hexgraph data="FFCC33"] will display the following:

RED 100% (255)
GREEN 80% (204)
BLUE 20% (51)

Download the Code

Examples from this page can be downloaded here .

Shortt URL for this post:

Leave a Reply

Your email address will not be published. Required fields are marked *