29

I'm trying to use a PHP variable to add a href value for a link in an echo statement.

Here's a simplified version of the code I want to use. I know that I can't just add the variable into the echo statement, but I can't seem to find an example anywhere that works.

$link_address = '#';
echo '<a href="$link_address">Link</a>';
Dharman
  • 30,962
  • 25
  • 85
  • 135
jasonbradberry
  • 853
  • 2
  • 17
  • 30

8 Answers8

73

Try like

HTML in PHP :

echo "<a href='".$link_address."'>Link</a>";

Or even you can try like

echo "<a href='$link_address'>Link</a>";

Or you can use PHP in HTML like

PHP in HTML :

<a href="<?php echo $link_address;?>"> Link </a>
GautamD31
  • 28,552
  • 10
  • 64
  • 85
11

you can either use

echo '<a href="'.$link_address.'">Link</a>';

or

echo "<a href=\"$link_address\">Link</a>';

if you use double quotes you can insert the variable into the string and it will be parsed.

Davide De Santis
  • 922
  • 1
  • 10
  • 25
5

Basically like this,

<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>
BSMP
  • 4,596
  • 8
  • 33
  • 44
4

as simple as that: echo '<a href="'.$link_address.'">Link</a>';

Jay
  • 3,353
  • 5
  • 25
  • 34
0

You can use one and more echo statement inside href

<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>

link : "/profile.php?usr=firstname&email=email"

imsing
  • 7
  • 2
0

This worked much better in my case.

HTML in PHP: <a href=".$link_address.">Link</a>

NDi
  • 184
  • 1
  • 2
  • 17
0

The safest way to generate links in PHP is to use the built-in function http_build_query(). This function is very easy to use and takes an array as an argument.

To create a dynamic link simply echo out the result of http_build_query() like so:

$data = [
    'id' => $id,
    'name' => $name
];

echo '<a href="index.php?'.http_build_query($data).'">Link</a>';
Dharman
  • 30,962
  • 25
  • 85
  • 135
-2

If you want to print in the tabular form with, then you can use this:

echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;
Hashmat
  • 149
  • 1
  • 11
Alaa Moneam
  • 509
  • 5
  • 10