How to add URL in echo statement in PHP?

Its really interesting to know How to add URL in echo statement in PHP?

When I was working on one code in PHP I was asked by a student to check his small code written on a piece of paper – yes, I always instruct the students to first write their code on paper first.

As I was busy with my own complicated coding I just looked at his code and said that it was ok! He had written in like this –

add_action("wp_footer", "vsa_Add_Text");
// Define 'vsa_Add_Text'
function vsa_Add_Text()
{
  echo "<a href = https://www.google.com>Google</a>"; 
}

Now initially if you look at the above code, it appears almost ok! Anyone can say that the echo statement will echo the string inside the “double quotes”, no matter may it be a link or whatever!

But the code is of course not correct!

Then what’s wrong with it?

The correct code should be as follows –

add_action("wp_footer", "vsa_Add_Text");
// Define 'vsa_Add_Text'
function vsa_Add_Text()
{
  echo "<a href='http://localhost/wordpress'>VSAcademy</a>"; 
}

This is because the echo statement or language construct has following important rules.

  1. echo is a statement is used to display the output.
  2. echo can be used with or without parentheses: echo().
  3. echo never returns any value.
  4. We can pass multiple strings separated by a comma (,) in echo.
  5. echo is faster than the print statement.

The common mistake that the students make is as follows, even though they know that you can’t add variable to echo statement. However, if you want to add it, then use double quotes to insert the variable into the string and it will be parsed.

$link_address = 'http://localhost/wordpress';
echo '<a href="$link_address">Link</a>';

So if you want to add HTML in PHP then it should be like this –

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

You can also make it other way round –

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

The other ways are –

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

Or like this also –

<?php
$link = "http://localhost/wordpress"; // Paste URL in double quotes
print "<a href="'.$link.'">VSAcademy</a>";
?>

Hope you liked this discussion. If you have any queries, please comment below.

Share on your network!
Dattaraj Vidyasagar
Dattaraj Vidyasagar

Author on this website. He is veteran of Core Electronics since last 36+ years. ATL Mentor of Change, Niti Ayog, Govt. of India, Google Certified Educator, International Robotics Trainer and author of 18 books on electronics, robotics, programming languages and web designing... ➤➤

Leave a Reply

Your email address will not be published. Required fields are marked *