1

I am trying to display a PHP variable within a <p> tag but I either keep getting errors or the name of the variable is shown but not it's content.

Here is the code:

echo '<div class="item" style="background-color:'.$row[colour].';width:'.$row[width].'px;"><a href="'.$row[link_url].'" title="'.$row[name].'"><p>$row[name]</p></a></div>';

Where I have written:

<p>$row[name]</p>

will not show up in the browser correctly and instead will just show the name of the variable. If I surround the variable with '' I get an error regaurding syntax.

I have also tried to echo the variable:

<p><?php echo $row[name] ?></p>

But on the website nothing is displayed at all and when I look in the FireFox inspector I see this: The code has automatically been commented out?

4 Answers 4

3

You need to add '. $row[name] . '

like this

echo '<div class="item" style="background-color:'.$row[colour].';width:'.$row[width].'px;"><a href="'.$row[link_url].'" title="'.$row[name].'"><p>' . $row[name]. '</p></a></div>';

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Just what I was looking for
2

You have to concatenate the php variable.

Replace

echo '<div class="item" style="background-color:'.$row[colour].
     ';width:'.$row[width].'px;"><a href="'.$row[link_url].
     '" title="'.$row[name].'"><p>$row[name]</p></a></div>';

with

echo '<div class="item" style="background-color:'.$row[colour].
     ';width:'.$row[width].'px;"><a href="'.$row[link_url].
     '" title="'.$row[name].'"><p>'.$row[name].'</p></a></div>';

Notice '"><p>'.$row[name].'</p></a></div>';

1 Comment

Thanks! This helped alot
2

When interpolating array values in strings you need to use curly brackets and double quotes.

echo ...."\"><p>{$row['name']}</p></a></div>";

When you use single quotes, php does not interpolate variable names inside the string. Instead, it just prints the names, which is what you're seeing in the source code.

And your array keys should be strings, so ['name'] instead of [name]

Comments

1

Not sure if this is 100% as I am half asleep but at least it will help you with your array a bit.

echo "<div class=\"item\" style=\"background-color:".$row['colour'].";width:".$row['width']."px;\"><a href=".$row['link_url']." title=".$row['name']."><p>".$row['name']."</p></a></div>";

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.