2

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

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
David Willis
  • 1,082
  • 7
  • 15
  • 23

6 Answers6

14

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
  • 28,143
  • 8
  • 66
  • 82
  • Thanks. I had tried the first already and it failed but concatenation worked a treat. $link is a double array so maybe that's why Thanks a lot! – David Willis Oct 23 '09 at 22:30
2

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
  • 5,428
  • 3
  • 29
  • 34
  • 4
    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 Oct 23 '09 at 22:40
  • Call me anal, but I also replace all common URL's with constants. – Daren Schwenke Oct 23 '09 at 22:47
  • 1
    @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 Oct 23 '09 at 23:45
  • This is not plausible. The difference in execution speed will be micro or nano-seconds, if it is even measurable. See e.g. http://stackoverflow.com/questions/13620/speed-difference-in-using-inline-strings-vs-concatenation-in-php5 – Rich Nov 14 '16 at 15:29
1

Needs double quotes:

$url = "www.example.com/$link";
Travis
  • 4,018
  • 4
  • 37
  • 52
1

Alternate way:

$url = "www.example.com/{$link}";
Chris Kloberdanz
  • 4,436
  • 4
  • 30
  • 31
1
$url = "www.example.com/$link";
AntonioCS
  • 8,335
  • 18
  • 63
  • 92
0

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,693
  • 1
  • 11
  • 17