RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

Generate a Random Color Value With PHP

Hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols: 0–9 to represent values zero to nine, and case-insensitive A, B, C, D, E, F to represent values ten to fifteen. Since colors are represented by HEX values between 0x000000 and 0xffffff (where 0x simply indicate the number is in hexadecimal), we simply select a random value between the two limits.

The following functions are just examples of how you might generate a random value from white to black. Since 0xffffff translates to a numeric value of 16777215, you can use it as an alternative to the HEX limit (with the former requiring a conversion back to the HEX value).

1
<?php 
2
/*
3
 Generate a Random Color Value With PHP
4
 http://www.beliefmedia.com/code/php-snippets/random-hex-color-php
5
*/
6
 
7
function bm_random_hex() {
8
 return '#' . dechex(rand(0x000000, 0xFFFFFF));
9
}
10
 
11
function bm_random_hex() {
12
 return '#' . str_pad(dechex(rand(0, 16777215)), 6, 0, STR_PAD_LEFT);
13
}
14
 
15
function bm_random_hex() {
16
 return sprintf('#%06x', rand(0, 16777215));
17
}
18
 
19
function bm_random_hex() {
20
 $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
21
 return '#' . $rand[rand(0,15)] . $rand[rand(0,15)] . $rand[rand(0,15)] . $rand[rand(0,15)] . $rand[rand(0,15)] . $rand[rand(0,15)];
22
}
23
 
24
/* Usage */
25
echo bm_random_hex();

Only one function should be used. The last function isn't overly efficient.

If you wanted to generate a random color value with RGB values (for example, rgb(255,255,255)), use the following:

1
<?php 
2
/*
3
 Generate a Random Color Value With PHP
4
 http://www.beliefmedia.com/code/php-snippets/random-hex-color-php
5
*/
6
 
7
function bm_random_rgb() {
8
 return 'rgb(' . rand(0, 255) . ',' . rand(0, 255) . ',' . rand(0, 255) . ')';
9
}

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment