Navigate back to the homepage

Convert hexadecimal color to rgb or rgba in php

Vishnu Damwala
February 7th, 2020 · 1 min read

Below PHP helper function converts hex color code string into RGB or RGBA color.

Code:

1/**
2 * Convert hexadecimal color to rgb or rgba
3 *
4 * @param string $color
5 * @param boolean $getRGBA
6 * @param float $opacity
7 * @return string
8 */
9 function hex2rgba(
10 string $color,
11 bool $getRGBA = true,
12 float $opacity = 1
13 ): string {
14 $output = 'rgb(0,0,0)';
15
16 // Return default color if no color is provided
17 if (!$color) {
18 return $output;
19 }
20
21 // Sanitize $color if "#" is provided
22 if ($color[0] == '#') {
23 $color = substr($color, 1);
24 }
25
26 // Check if color has 6 or 3 characters and get values
27 if (strlen($color) == 6) {
28 $hex = [
29 $color[0] . $color[1],
30 $color[2] . $color[3],
31 $color[4] . $color[5],
32 ];
33 } elseif (strlen($color) == 3) {
34 $hex = [
35 $color[0] . $color[0],
36 $color[1] . $color[1],
37 $color[2] . $color[2],
38 ];
39 } else {
40 return $output;
41 }
42
43 //Convert hexadecimal color to rgb
44 $rgb = array_map('hexdec', $hex);
45
46 //Check for opacity(rgba or rgb)
47 if ($getRGBA) {
48 $rgb[] = (abs($opacity) > 1) ? 1 : $opacity;
49 $output = 'rgba(';
50 } else {
51 $output = 'rgb(';
52 }
53
54 $output .= implode(',', $rgb) . ')';
55 //return rgb(a) color string
56 return $output;
57 }

More articles from MeshWorld

Get Array of IDs from Eloquent Collection in Laravel

Get an array of ids from Eloquent collection in Laravel using pluck() and modelKeys() function

January 2nd, 2020 · 1 min read

Write a Program to print Hello, World! in JAVA

A program to print "Hello World!" in JAVA.

January 2nd, 2020 · 1 min read
© 2017–2020 MeshWorld
Link to $https://twitter.com/meshworldindiaLink to $https://facebook.com/meshworldindiaLink to $https://instagram.com/meshworld.india/