I am pretty new to php but I'm stuck on this problem... Say i wait to put a link to another site with a given parameter, how do I do it correclty?
This is what i have now:
<html>
<body>
<?php
$param = "test";
echo "<a href="http://www.whatever.com/$param">Click Here</a>;
?>
</body>
</html>
HI Jasper,
you can do this:
<?
sprintf("<a href=\"http://www.whatever.com/%s\">Click Here</a>", $param);
?>
You can embed a variable into a double quoted string like my first example, or you can use concantenation(the period) like in my second example:
echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";
echo '<a href="http://www.whatever.com/' . $param . '">Click Here</a>';
Notice that I escaped the double quotes inside my first example using a backslash.
There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
<a href="<?= $link ?>">Click here to go to Google.</a>
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
Heredoc may be an option, see example 2 here: http://php.net/manual/en/language.types.string.php
I recommend using the short ' instead of ". If you do so, you wont longer have to escape the double quote (\").
In that case you would write
echo '<a href="http://www.whatever.com/'. $param .'">Click Here</a>';
But look onto nicolaas' answer "what you really should do" to learn how to produce cleaner code.
You can do it a number of ways, depending on the type of quotes you use:
echo "<a href='http://www.whatever.com/$param'>Click here</a>";
echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";
Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n
will be expanded to mean the new line character, it will just be the characters \
and n
in sequence.
You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.
On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.
Source: Stackoverflow.com