Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP echo variable and html together

Tags:

php

I know this is a basic php question, but I'm having trouble showing variables inside an echo of HTML. Below is what I'm trying to achieve.

<?php
    $variable = 'testing';
    echo <span class="label-[variable]">[variable]</span>
?>

should output:

<span class="label-testing">testing</span>
like image 661
cusejuice Avatar asked Feb 09 '13 19:02

cusejuice


2 Answers

<?php
    $variable = 'testing';
    echo <span class="label-[variable]">[variable]</span>
?>

Should be

<?php
    $variable = 'testing';
    echo '<span class="label-' . $variable .'">' . $variable . '</span>';
?>
like image 116
Julio Avatar answered Sep 24 '22 13:09

Julio


If your HTML contains double quotes, then you can wrap it in single quotes:

echo '<span class="label-' . $variable . '">' . $variable . '</span>';

Additionally, you can do it inline by escaping the double quotes:

echo "<span class=\"label-$variable\">$variable</span>";

Using double quotes also allows for special characters such as \n and \t.

The documentation is your friend.

like image 33
Kermit Avatar answered Sep 21 '22 13:09

Kermit