Search code examples
phphtmlcolorsecho

How to store a PHP variable in a HTML attribute?


I want to create a page which allows a user to select colours (among the listed ones, via checkboxes). When the user clicks on the submit button, all the selected colours should get displayed with their corresponding colours as their font colour.

Here is my code:

<?php 
if(!isset($_POST['button'])) { 
?>
    Colours<br>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method=post>
    <input type="checkbox" name="colours[]" value="Red">Red<br>
    <input type="checkbox" name="colours[]" value="Blue">Blue<br>
    <input type="checkbox" name="colours[]" value="Green">Green<br>
    <input type="checkbox" name="colours[]" value="Yellow">Yellow<br>
    <input type="checkbox" name="colours[]" value="Pink">Pink<br>
    <input type="submit" name="button" value="Show"> </form>
    <?php
} else {
    if (isset($_POST['colours'])) {
        echo "Colours selected are:<br><UL type=circle>";
        foreach($_POST['colours'] as $color) 
            echo "<LI><font color='echo $color'; >$color</font>";
        echo"</UL>";
    } else { 
        echo "No colour selected"; 
    }
} 
?>

There is a bug somewhere, the font colors are not as expected. I want it like this image below:

Screenshot


Solution

  • When appending a string to variable or another string, you must concatenate the values with a . (dot). for example:

    echo("<li><font color=".$color.">".$color."</font>");