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

2
  • Did we all posted at the same time? I swear when I saw this question there was no answer and now there are 5 lol Commented Oct 23, 2009 at 22:28
  • You can use this script PHP: eval.in/608533 Commented Feb 20, 2018 at 22:17

6 Answers 6

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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!
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.

4 Comments

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.
Call me anal, but I also replace all common URL's with constants.
@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.
This is not plausible. The difference in execution speed will be micro or nano-seconds, if it is even measurable. See e.g. stackoverflow.com/questions/13620/…
1

Needs double quotes:

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

Comments

1

Alternate way:

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

Comments

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

Comments

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.

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.