Manolo
Manolo

Reputation: 26370

Convert an hexadecimal number to a string

I'm trying to convert an hexadecimal number into correct css formating:

$white = hexdec('#ffffff');

//Loops for a bunch of colours
for( $i = 0 ; $i <= $white ; $i=$i+5000 ) 
{
    //set default css background-color property
    $backgroundValue = dechex( $i );

    //if there are less of 7 characters (ex. #fa444, or #32F, ...)  
    if( $numLen = strlen( dechex( $i )) < 7 ) 
    {
        //insert (7 - numbers of characters) number of zeros after # 
        for ( $j = 0 ; $j < 7 - $numLen ; $j++ )
            $backgroundValue = strtr( $backgroundValue, '#', '#0' );                
    }
    //echo each div with each background-color property. 
    echo '<div class="colour" style="width: 10%; float: left; background: '.$backgroundValue.';">'.dechex($i).'</div>';
}

But this doesn't work. How could I turn the hexadecimal number into a string like: #FFFFFF .

Update:

The problem was that I wasn't passing the # to the start of the string: $backgroundValue = '#'.dechex( $i );.

This code is working fine:

        $white = hexdec('#ffffff');
        for( $i = 0 ; $i <= $white ; $i=$i+10000 ) 
        {
            $backgroundValue = '#'.dechex( $i );
            $numLen = strlen( dechex( $i ));

            if( $numLen < 6 ) 
            {

                for ( $j = 0 ; $j < (6 - $numLen) ; $j++ )
                    $backgroundValue = str_replace( '#', '#0', $backgroundValue );              
            }

            echo '<div class="colour" style="width: 10%; float: left; background: '.$backgroundValue.';">'.$backgroundValue.'</div>';
        } 

Upvotes: 0

Views: 185

Answers (1)

Philipp
Philipp

Reputation: 15629

Why not simply use str_repeat?

$end = 0xffffff;

for ($i = 0; $i < $end; $i += 5000) {
    $color = (string) dechex($i);
    $backgroundValue = '#' . str_repeat('0', 6 - strlen($color)) . $color;
    echo '<div class="colour" style="width: 10%; float: left; background: '.$backgroundValue.';">'.dechex($i).'</div>';
}

you could also use sprintf

$backgroundValue = sprintf('#%06x', $i);

Upvotes: 1

Related Questions