0

I'm trying to use an array to determine the colors in a table... However, I believe my syntax is incorrect...

Array :

$colors = [
  1 => "red",
  2 => "yellow",
  3 => "green",
];

HTML/PHP :

<td bgcolor=\"$colors[$row['form1']]\">".$row["form1"]."</td>

Any help is appreciated, thanks!

13
  • What is $row['form1']? Commented Jan 9, 2016 at 9:28
  • @Nouphal.M it is an imported value from my MYSQL database, the database holds values ranging from 1-3 Commented Jan 9, 2016 at 9:29
  • which color you need to show from array ? does form1 gives any colour name' Commented Jan 9, 2016 at 9:30
  • But what is it? integer or string? Commented Jan 9, 2016 at 9:30
  • 1
    @Michael Thank you! This worked perfectly !!! Commented Feb 19, 2016 at 19:40

7 Answers 7

1

Try the below

$doc= new DOMDocument(); $doc->loadHTML($html); $colors = array(1 => "red",2 => "yellow",3 => "green");foreach ($doc->getElementsByTagName('td') as $td) {if ($td->getAttribute('bgcolor'),$colors) { /* if true then any color in the array is equal to the td's bgcolor*/ } }
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

<?php echo '<td bgcolor="'.$colors[intval($row['form1'])].'">'.$row["form1"].'</td>'; ?>

Comments

0

Try This code will work for

<?php
$colors = array(1 => "red", 2 => "yellow", 3 => "green");

$form1=1;
?>

<table border="1">
    <thead>
    <td>name</td> 
    <td>Class</td>
</thead>
<tbody>
    <tr>
        <td bgcolor='<?php echo $colors[$form1]; ?>'>test</td> 

        <td>bcs</td> 
    </tr>
    <tr>
        <td>temp</td> <td>mcs</td>
    </tr>
</tbody>
</table>

change $form1 varibale value dynamicaly as you want.

Comments

0

try this bro.

 <?php

$colors =  array(
    1 => "red",
    2 => "yellow",
     3 => "green",
);

    ?>
    <html>
    <body bgcolor="<?php $row["form1"]=1;// replace it . i have assigned it as 1
    $r=$row["form1"];
    echo $colors[$r];?>"><?php echo $r; ?> 
 </body>

</html>

Comments

0

First check array is created in right way means there is any error in it....and $row['form1'] value is in correct format

to print array print_r($colors);exit;

after that this will work

$colors = array(1=>"red",2 => "yellow",3 => "green");

        <tr>
            <td bgcolor="<?php echo $colors[2];?>"><?php echo $colors[2]; ?></td>
        </tr>         

Comments

0

Please try in this way :

<td bgcolor="<?php echo $colors[$row['form1']]; ?>"><?php echo $row['form1']; ?></td>

1 Comment

No luck:( Thank you though!
0

First create an array

$colors =  array("a" => "red", "b" => "yellow","c" => "green");

HTML code with PHP

<td bgcolor="<?php echo $colors['a'];?>"> <?php echo $row['form1'] ?> </td>

Hope this will help you.

Comments

Your Answer

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