Skip to content

Instantly share code, notes, and snippets.

@AzureFlow
Created January 23, 2021 06:43
Show Gist options
  • Save AzureFlow/4f9f68541b12e8894b34fcc35201f1cc to your computer and use it in GitHub Desktop.
Save AzureFlow/4f9f68541b12e8894b34fcc35201f1cc to your computer and use it in GitHub Desktop.
Easy way to apply colors to console output in PHP
<?php
class Colors
{
public static function getRich(string $string, string $foregroundColor = null, string $backgroundColor = null): string
{
$coloredString = '';
if(!empty($foregroundColor))
{
$coloredString .= "\033[" . $foregroundColor . 'm';
}
if(!empty($backgroundColor))
{
$coloredString .= "\033[" . $backgroundColor . 'm';
}
return $coloredString . $string . "\033[0m";
}
}
class ConsoleForeground
{
public const BLACK = '0;30';
public const DARK_GRAY = '1;30';
public const BLUE = '0;34';
public const LIGHT_BLUE = '1;34';
public const GREEN = '0;32';
public const LIGHT_GREEN = '1;32';
public const CYAN = '0;36';
public const LIGHT_CYAN = '1;36';
public const RED = '0;31';
public const LIGHT_RED = '1;31';
public const PURPLE = '0;35';
public const LIGHT_PURPLE = '1;35';
public const BROWN = '0;33';
public const YELLOW = '1;33';
public const LIGHT_GRAY = '0;37';
public const WHITE = '1;37';
}
class ConsoleBackground
{
public const BLACK = '40';
public const RED = '41';
public const GREEN = '42';
public const YELLOW = '43';
public const BLUE = '44';
public const MAGENTA = '45';
public const CYAN = '46';
public const LIGHT_GRAY = '47';
}

echo Colors::getRich('Cyan', ConsoleForeground::LIGHT_CYAN) . PHP_EOL;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment