How to insert a variable into a link in PHP
Introduction
Beginner developers, or rather webmasters, often need
to create small templates reusable in different site directories.
To speed up development it helps to insert variables into links
| Introduction | |
| PHP code example | |
| Result | |
| Code comments | |
| Link into a variable |
PHP code example
Suppose the variables
$var_page_lang and
$var_page_country you get from outside.
They must go into the href attribute
<?php
$url = "https://www.heihei.ru/$var_page_lang/$var_page_country/";
echo'
<a href="'.$url.'">
'.$var_page_country.'
</a>
';
Result
Suppose the country is Finland and the language is ru.
Below a Finland link should appear leading to https://www.heihei.ru/ru/Finland/
Code comments
It is quite simple; note the missing dots around variable names in the string.
$url = "https://www.heihei.ru/$var_page_lang/$var_page_country/";
Why I point this out is explained in the next example.
Try the same without creating a separate $url variable - insert right into href
<?php
echo'
<a href="https://www.heihei.ru/'.$var_page_lang.'/'.$var_page_country.'">
'.$var_page_country.'
</a>
Result
The result should be the same.
So just remember: when adding variables in echo
dots and ' around the variable name are needed, but not when creating a separate variable.
Note that this memo is not a guide to action - better
to build the site right from the start instead of slapping PHP into html.
Link into a variable
If your goal is not inserting a variable into a link but just recording a link in a variable, it is simple
<?php
$url = 'https://www.heihei.ru';
?>
| PHP session locking | |
| Installing PHP frameworks | |
| Installing Yii | |
| Installing Symfony | |
| Installing Laravel | |
| Profiling PHP sites | |
| XDebug - debugging and profiling php code |