How to Use Colors in Command-line PHP Output

Josh Sherman
1 min read
Software Development PHP

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 "\e[0;31;42mMerry Christmas!\e[0m\n";

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 \033 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 [0;31;42m, this is what sets the foreground color (0;31) 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

Dark Grey1;30
Light Red1;31
Light Green1;32
Light Blue1;34
Light Magenta1;35
Light Cyan1;36
Light Grey0;37

Background Colors

Light Grey47

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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles