tags:

views:

254

answers:

6

Hello, I want to do define the following variable $url

$url = www.example.com/$link;

where $link is another predefined variable text string e.g. testpage.php

But the above doesn't work, how do I correct the syntax?

Thanks

+7  A: 

Try this:

$url = "www.example.com/$link";

When string is in double quotes you can put variables inside it. Variable value will be inserted into string.

You can also use concatenation to join 2 strings:

$url = "www.example.com/" . $link;
Ivan Nevostruev
Thanks. I had tried the first already and it failed but concatenation worked a treat.$link is a double array so maybe that's whyThanks a lot!
David Willis
+1  A: 

Needs double quotes:

$url = "www.example.com/$link";
Travis
A: 

It'd be helpful if you included the erroneous output, but as far as I can tell, you forgot to add double quotes:

$url = "www.example.com/$link";

You will almost certainly want to prepend "http://" to that url, as well.

Adam Bard
+1  A: 

Alternate way:

$url = "www.example.com/{$link}";
Chris Kloberdanz
+1  A: 
$url = "www.example.com/$link";
AntonioCS
+1  A: 

Hate to duplicate an answer, but use single quotes to prevent the parser from having to look for variables in the double quotes. A few ms faster..

$url = 'www.example.com/' . $link;

EDIT: And yes.. where performance really mattered in an ajax backend I had written, replacing all my interpolation with concatenation gave me a 10ms boost in response time. Granted the script was 50k.

Daren Schwenke
Is it *really* a few *milliseconds* faster? Frankly, this is precisely where variable interpolation is useful - sure, if you have a string with no variable interpolation in, use single quotes, but this seems like a ridiculous premature optimisation that slightly damages readability.
Rob
Call me anal, but I also replace all common URL's with constants.
Daren Schwenke
@Rob: Not to be be a moron, but... a few *milliseconds* is actually a huge deal in the programming world. If they stack up, you've got a slow script on your hands. Were you meaning *microseconds*? There's a big difference.
brianreavis