Putting php arrays into html tags

Tags: , ,



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.

Answer

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>';
}


Source: stackoverflow