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

↓ Contents ↓
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/

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.

Finland

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'; ?>

↓ Articles about PHP ↓
Development in PHP
Arrays in PHP
How to display various PHP timezones
json_decode PHP
How to get screen width with PHP
Calling a function from another file
Premature end of chunk coded message body: closing chunk expected
Generate unique random numbers in PHP
Find out your HTTP_USER_AGENT
Compare two dates
Classes in PHP 8
Authentication and authorization in PHP 8
↓ Other articles ↓
PHP session locking
Installing PHP frameworks
Installing Yii
Installing Symfony
Installing Laravel
Profiling PHP sites
XDebug - debugging and profiling php code
Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: