1

I would like to know how to append a variable to a link in PHP. I am grabbing the parameter by using $lang = $_GET['lang'];.

I would like to append the $lang variable to the link like below.

<li><a href="/categories/?lang=$lang">Categories</a></li>

5 Answers 5

1

You can use the PHP function http_build_query

http://php.net/manual/en/function.http-build-query.php

--EDIT--

<?php 
$url = "/categories/?";
$querystring_parameters = array('lang'=>$_GET['lang']);
$url .=  http_build_query($querystring_parameters);

?>
<li><a href="<?php echo $url; ?>">Categories</a></li>
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, I edited my answer with a basic example (with context of the OP)
You could even initialize the array before you add / overwrite the lang value: $querystring_parameters = $_GET;. Or only use $_GET ;-)
Yes, but the OP should be sure that the page is called always (and only) with the qs param 'lang', this case would be like giving too much trust the the end user
I would also add a filter_input(INPUT_GET, 'lang') and then check if the value is set/empty/valid, I don't know if it would seem too paranoic :)
http_build_query will correctly encode the string but even if it didn't, the visitor would only be messing with themselves. But it is definitely always good to think about and if you don't need anything else, don't add it.
0

Just echo it in PHP like:

<li><a href="/categories/?lang=<?php echo $lang; ?>">Categories</a></li>

Comments

0

Try this:

<li><a href="/categories?lang=<?php echo $lang; ?>&var1=<?php echo $value1; ?>">Categories</a></li>

OR

<?php echo '<li><a href="/categories?lang=$lang&var1=$value1">Categories</a></li>'; ?>

Comments

0

You mean like this?

Echo "<li><a href='/categories/?lang=".$lang."'>Categories</a></li>";

The ". and ." means it escapes string so $lang is the value of $lang.

EDIT:The above code needs to be inside php tags. So:

<?php
Echo "<li><a href='/categories/?lang=".$lang."'>Categories</a></li>";
?>

Comments

0

Try this:-

<li><a href="/categories/?lang=<?php echo $lang; ?>">Categories</a></li>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.