1

I am trying to make a table that has different colors for each of its columns. There will be four columns.

            $colors = array("background-color:red;", "background-color:gold", "background-color:pink;", "background-color:purple;");
            $html = '<table>';

            foreach( $array as $key=>$value){
                $html .= '<tr style="background-color:white;">';
                foreach($value as $key2=>$value2){
                    $html .= '<td>' . htmlspecialchars($value2) . '</td>';
                }
                $html .= '</tr>';
            }

I created an array called colors that has the strings of the colors I want, but I don't know how to put that into the tag. I tried typing it in there, but since it is a string, it takes it as text instead of as code. Where it says "background-color:white;", I'd like it to call the values from the array instead. Thanks.

1
  • What have you tried so far? Where are you stuck? How should the resulting markup look like? Commented Apr 14, 2021 at 8:51

1 Answer 1

1

You can array_pop for this provided you have exactly 4 columns. You also can't apply background colours to <tr> like that, you need to apply them to the <td>

$colors = array("background-color:red;", "background-color:gold", "background-color:pink;", "background-color:purple;");
$html = '<table>';

foreach( $array as $key=>$value){
    $color = array_pop($colors);
    $html .= "<tr>";
    foreach($value as $key2=>$value2){
        $html .= "<td style='{$color}'>" . htmlspecialchars($value2) . '</td>';
    }
    $html .= '</tr>';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.