Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Using a variable inside a double quotes

Tags:

php

please check the following code.

$imagebaseurl = 'support/content_editor/uploads/$name'; 

The $imagebaseurl is a variable that is containing a link to my image folder (uploads) and inside the folder I have some other folders which are named after my users name. for example: I have a user who's name is john, so the the link should look like this-> support/content_editor/uploads/john.

The main idea is when any user is logged in and browses his image gallery I want to take him to his own gallery which basically is named after his name.

When he will visit the gallery the value of $name in the link will come from the user's login name (from session). Now the problem is as you probably have already understood that the placement of $name in the above link is wrong and that is why it is not working. I am getting this whole URL> (support/content_editor/uploads/$name) instead of (support/content_editor/uploads/john)

Now could you please tell me how to use the $name in this $imagebaseurl = 'support/content_editor/uploads/$name';

like image 915
black_belt Avatar asked May 09 '12 08:05

black_belt


People also ask

How do you use double quotes in a variable?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

How do you put a variable in a string in PHP?

We can use a template string in PHP to concatenate a variable and a string. We use curly braces for the interpolation. The curly braces contain the variable, and we write the string that needs to be interpolated right after the curly braces. The variable inside the curly braces is the placeholder for the value.

Can you use single and double quotes in PHP?

In PHP, people use single quote to define a constant string, like 'a' , 'my name' , 'abc xyz' , while using double quote to define a string contain identifier like "a $b $c $d" . echo "my $a"; This is true for other used of string.


1 Answers

$imagebaseurl = 'support/content_editor/uploads/' . $name; 

or

$imagebaseurl = "support/content_editor/uploads/{$name}"; 

Note that if you use double quotes, you can also write the above as:

$imagebaseurl = "support/content_editor/uploads/$name"; 

It's good though to get in the habit of using {$...} in double quotes instead of only $..., for times where you need to insert the variable in a string where it's not obvious to PHP which part is the variable and which part is the string.

If you want the best performance, use string concatenation with single quotes.

like image 61
rid Avatar answered Sep 23 '22 11:09

rid