All I want to do is echo out a PHP variable inside a <li>
tag. Refer to the code below. What's the proper format? Mine is not working.
$row['cat_title'];
echo "<li> {$cat_title} </li>";
All I want to do is echo out a PHP variable inside a <li>
tag. Refer to the code below. What's the proper format? Mine is not working.
$row['cat_title'];
echo "<li> {$cat_title} </li>";
If you need to output a value of a particular array key (e.g. $row['cat_title']
) in HTML, you have quite a few options.
You can use the concatenation operator (.
):
echo '<li>' . $row['cat_title'] . '</li>';
You can use variable interpolation with simple string parsing (note that in this syntax, quotes around the array key must be omitted):
echo "<li>$row[cat_title]</li>";
You can use variable interpolation with complex string parsing (using {}
) which is actually not necessary here, but useful for more interpolating more complex expressions. With this syntax, quotes around the array key should be included.:
echo "<li>{$row['cat_title']}</li>";
You can output plain HTML and use the echo shortcut syntax <?=
to output the value (only do this if you are already outputting HTML, not if you are currently in a <?php
tag; that would be a syntax error.):
<li><?= $row['cat_title'] ?></li>
You can use printf
(thanks to Elias Van Ootegem's comment for reminding me of this; I should have included it to begin with). sprintf
can be used if you want to save the result to a variable instead; printf
will output it immediately:
printf('<li>%s</li>', $row['cat_title']);
The first argument of printf
is a format string, where %s
is a string conversion specification that will take the value of $row['cat_title']
when printf
is executed.
There are other ways, but these are the most common.
echo '<li>'.$var.'</li>';
OR
echo "<li>$var</li>";
OR
<li><?=$var?></li>
You need to reference the right variable. You're on the right track, though.
echo "<li> {$row['cat_title']} </li>";
If the file is mostly PHP in the file then:
<?php echo "<li>" . $row['cat_title'] . "</li>"; ?>
Or conversely if it's mostly HTML in the file then:
<li><?php echo $row['cat_title']; ?></li>
It sounds to me that it's most likely the second option you are looking for.
Another alternative:
<li><?php echo $row['cat_title']; ?></li>
Either of these methods will work...
// Use single quotes and periods like this...
echo '<li>'. $row['cat_title'] .'</li>';
OR
// Use double quotes like this...
echo "<li> $row['cat_title'] </li>";