Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Nov 2005
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Generating Hex Codes

    I have a function here that generates hex codes for the use of inputing them into html for colors. The function works great, my problem is that sometimes the code it generates ends up a 5 digit hex code, which firefox dosn't like. Any suggestions on how I can ensure that each hex value created is two digits?

    function randColor(){

    $r= rand(0,255);
    $g= rand(0,255);
    $b= rand(0,255);
    $rhex = dechex($r);
    $ghex = dechex($g);
    $bhex = dechex($b);
    $color = $rhex . $ghex . $bhex;
    return $color;

    }

  • #2
    Senior Coder
    Join Date
    Nov 2002
    Location
    North-East, UK
    Posts
    1,265
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You could put a bit of validation in
    PHP Code:
    <?php 
    function randColor(){

    $rrand(0,255);
    $grand(0,255);
    $brand(0,255);
    $rhex dechex($r);
    $ghex dechex($g);
    $bhex dechex($b);
    $color $rhex $ghex $bhex;

        if(
    strlen($color) == 6){
            return 
    $color;
        }

    for(
    $x=0$x<10$x++){
        
    $col randColor();
        if(
    $col != ""){
            echo 
    '<span style="color: #' $col '">' $col '</span>';
            echo 
    '<br>' "\r\n";
        }
    }
    ?>

  • #3
    Regular Coder
    Join Date
    Jun 2004
    Posts
    565
    Thanks
    0
    Thanked 18 Times in 18 Posts
    PHP Code:
    function randColor()
    {
      return 
    randomColorValue().randomColorValue().randomColorValue();
    }
    function 
    randomColorValue()
    {
      return 
    str_pad(dechex(rand(0255)), 2'0'STR_PAD_LEFT);

    dumpfi


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •