Vidyasagar Academy Wishes a Very Happy, Healthy & Prosperous Diwali to all our Students & Teachers!
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.
- echo is a statement is used to display the output.
- echo can be used with or without parentheses: echo().
- echo never returns any value.
- We can pass multiple strings separated by a comma (,) in echo.
- 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.