Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Add PHP variable inside echo statement as href link address?
In PHP, you can include variables inside echo statements to create dynamic href link addresses. There are several approaches depending on whether you're using PHP within HTML or generating HTML from PHP.
Method 1: Concatenation with Echo
Use string concatenation to combine the variable with the HTML anchor tag ?
<?php $link_address = "https://www.tutorialspoint.com"; echo "<a href='" . $link_address . "'>Visit TutorialsPoint</a>"; ?>
<a href='https://www.tutorialspoint.com'>Visit TutorialsPoint</a>
Method 2: Variable Interpolation
PHP automatically interpolates variables inside double quotes ?
<?php $link_address = "https://www.tutorialspoint.com"; echo "<a href='$link_address'>Visit TutorialsPoint</a>"; ?>
<a href='https://www.tutorialspoint.com'>Visit TutorialsPoint</a>
Method 3: PHP in HTML
When mixing PHP with HTML, use PHP tags to output the variable directly ?
<?php $link_address = "https://www.tutorialspoint.com"; ?> <a href="<?php echo $link_address; ?>">Visit TutorialsPoint</a>
Method 4: Using printf()
For more control over formatting, use printf() with placeholders ?
<?php
$link_address = "https://www.tutorialspoint.com";
$link_text = "Visit TutorialsPoint";
printf('<a href="%s">%s</a>', $link_address, $link_text);
?>
<a href="https://www.tutorialspoint.com">Visit TutorialsPoint</a>
Conclusion
All methods achieve the same result − embedding PHP variables in href attributes. Use concatenation for simple cases, variable interpolation for readability, and printf() for complex formatting with multiple variables.
Advertisements
