Link to home
Start Free TrialLog in
Avatar of keks_
keks_

asked on

inserting variable in a link

This should be a very easy question for you php ninjas.

I want to create a variable in my webpage, like this?

<%php i=100; %>

<a href="http://www.test.com/?=<%php i %>" >link 100</a>

What is the exact code to declare the variable and use it in a link so that the resulting link is http://www.test.com/?=100

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Actually, if you want the URL as the text of the link as well then


<a href="http://www.test.com/?=<?php echo $i; ?>" >http://www.test.com/?=<?php echo $i; ?></a>

or you can create a function:
<?php

function createHyperlink($path, $text) {
    return "<a href = '$path'>$text</a>";
}
?>

<?php echo createHyperlink("http://www.google.co.uk", "A link to google"); ?>

Open in new window

Some introductory help with PHP is available here: http://us.php.net/tut.php

Another way of doing this is to use HEREDOC notation.  I like HEREDOC because it helps me keep logic and presentation separated.


// UNTESTED CODE BUT VALID IN PRINCIPLE

// SET VALUE FOR ARGUMENT IN STRING NOTATION
$i = '100';

// ALL URL VARIABLES MUST BE URLENCODED
$url_i = urlencode($i);

// DECLARE THE LINK USING HEREDOC
$link = <<<LINK
<a href="http://www.test.com/?=$url_i" >link 100</a>
LINK;

// SHOW THE LINK
echo $link;

Open in new window

Sidebar note.  You might want to try that URL something more like this...
<a href="http://www.test.com?q=$url_i" >

In your test.com/index.php script you will find a variable named $_GET["q"] with a value equal to the contents of $url_i