Agrikk
Agrikk

Reputation: 69

Why is PHP producing garbled HTML for my table code?

I have created a heatmap function that I am going to use to fill the cells of a table in html using PHP 7.2.

Here is my function:

function bg($latency) {
    if ($latency ==0) {echo '#11FFFF';} 
    elseif ($latency <30) {echo '#22FFFF';} 
    elseif ($latency <60) {echo '#33FFFF';} 
    elseif ($latency <90) {echo '#44FFFF';} 
    elseif ($latency <120) {echo '#55FFFF';} 
    elseif ($latency <150) {echo '#66FFFF';} 
    elseif ($latency <180) {echo '#77FFFF';} 
    elseif ($latency <210) {echo '#88FFFF';} 
    elseif ($latency <240) {echo '#99FFFF';} 
    elseif ($latency <270) {echo '#AAFFFF';} 
    elseif ($latency <300) {echo '#BBFFFF';} 
    elseif ($latency >=300) {echo '#CCB27F';} 
}

I pull values from a MySQL table with a simple select statement and then try to build the table with the following code snippet:

while($row = mysqli_fetch_assoc($result)) {
    echo '<tr><td>'.$row['origin'].'</td><td bgcolor='.bg($row['lt01']).'>'.$row['lt01'].'</td></tr>';
}

But for some reason the output is garbled with the function output appearing before the HTML source:

#11FFFF<tr><td>LT01</td><td bgcolor=>0</td></tr>
#22FFFF<tr><td>LT02</td><td bgcolor=>11</td></tr>
#44FFFF<tr><td>LT03</td><td bgcolor=>62</td></tr>
#44FFFF<tr><td>LT04</td><td bgcolor=>74</td></tr>
#99FFFF<tr><td>LT05</td><td bgcolor=>214</td></tr>

I cannot for the life of me figure this out.

Upvotes: 0

Views: 59

Answers (1)

Austen Holland
Austen Holland

Reputation: 1978

This is because your bg function is echoing the colour code to the screen instead of returning it to be used by your other PHP code. Change the function to use return instead of echo and it will work as expected.

function bg($latency) {
    if ($latency == 0)       {return '#11FFFF';} 
    elseif ($latency < 30)   {return '#22FFFF';} 
    elseif ($latency < 60)   {return '#33FFFF';} 
    elseif ($latency < 90)   {return '#44FFFF';} 
    elseif ($latency < 120)  {return '#55FFFF';} 
    elseif ($latency < 150)  {return '#66FFFF';} 
    elseif ($latency < 180)  {return '#77FFFF';} 
    elseif ($latency < 210)  {return '#88FFFF';} 
    elseif ($latency < 240)  {return '#99FFFF';} 
    elseif ($latency < 270)  {return '#AAFFFF';} 
    elseif ($latency < 300)  {return '#BBFFFF';} 
    elseif ($latency >= 300) {return '#CCB27F';} 
}

echo is used when you want to display content to the screen right now. Due to how the PHP parser works, the echo in the bg function will run before the echo that called the function, as the parent echo has yet to finish. This is where return comes in. Instead of printing the content to the screen right now, it passes it back to whatever called the function to be used in whatever way you wish.

A more detailed explanation on echo vs return can be found in this post: What is the difference between PHP echo and PHP return in plain English?

Upvotes: 3

Related Questions