How to Use Colors in Command-line PHP Output

Nothing spruces up command-line output the way colors do. Just like when you’re
customizing your [Bash] prompt, you can use color codes in strings to colorize
your output. Keep in mind, these colors will only work on the command-line and
not in a browser. First let’s take a look at the syntax:

echo "ee[0mn"

The above command will echo out “Merry Christmas!” in a red font with a green
background. The first part of the string, e is the escape character and could
alternatively be represented by 33 in octal or using the function call
chr(27) if you want to close and reopen the string a bunch of times.

Next up is , this is what sets the foreground color () and the
background (42). This is all followed up by the text we’re colorizing. After
that is another color declaration that will reset the color to the terminal’s
default colors (usually grey text on a black background).

So now that we know how to colorize text, let’s take a look at all of the colors
that are available. All in there are 16 different foregrounds and 8 backgrounds.
Of the foregrounds, they are split between a normal colors and lighter alternate
versions that actually end up being displayed differently depending on the
terminal being used. Sometimes they are heavier text, sometimes alternative
colors. The colors and codes are as follows:

Foreground Colors

Color Code
Black
Dark Grey
Red
Light Red
Green
Light Green
Brown
Yellow
Blue
Light Blue
Magenta
Light Magenta
Cyan
Light Cyan
Light Grey
White

Background Colors

Color Code
Black 40
Red 41
Green 42
Yellow 43
Blue 44
Magenta 45
Cyan 46
Light Grey 47

It’s worth noting that you actually don’t need to set both the foreground and
the background color, if you wanted to you could simply set one or the other
using the aforementioned codes. When defining both, you must specify the
foreground color first and just separate the codes with a semi-colon.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.