Skip to content

Instantly share code, notes, and snippets.

@hcortezr
Last active August 22, 2017 06:08
Show Gist options
  • Save hcortezr/419403e7515d3372ac18c15cc631f292 to your computer and use it in GitHub Desktop.
Save hcortezr/419403e7515d3372ac18c15cc631f292 to your computer and use it in GitHub Desktop.
<?php
/**
* ColorConverter
* @author eDroid
* @link https://edroidthedev.com
*/
class ColorConverter {
/**
* Hex to RGB
*
* @param string $hex The hex value to convert. (ex. #ffffff)
*/
public function to_rgb(string $hex): array {
$h = substr($hex, -6);
return [hexdec(substr($h, 0, 2)), hexdec(substr($h, 2, 2)), hexdec(substr($h, 4, 2))];
}
/**
* RGB to Hex
*
* @param array $rgb The rgb value to convert. (ex. Array([0] => 255, [1] => 255, [2] => 255))
*/
public function to_hex(array $rgb): string {
return "#" . dechex($rgb[0]) . dechex($rgb[1]) . dechex($rgb[2]);
}
}
?>
<?php
require_once('ColorConverter.php');
$converter = new ColorConverter;
$hex = "#BADA55";
$rgb = array(186, 218, 85);
print_r($converter->to_rgb($hex)); // [186, 218, 85]
print_r($converter->to_hex($rgb)); // #bada55
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment