user1037871
user1037871

Reputation: 543

Working with a Variable in PHP

Please tell me what I am doing wrong, when the php file executes is saves the actual folder as "$name" instead of Peter. What am I doing wrong?

Here is my code:

$name = "Peter";
copy_directory('you/','dir/$name');

Upvotes: 0

Views: 128

Answers (5)

Risto Novik
Risto Novik

Reputation: 8295

Problem is that you use the ' but should use there "" or 'dir/'. $name:

copy_directory('you/','dir/$name');

Upvotes: 2

Somnath Muluk
Somnath Muluk

Reputation: 57656

It's good practice to use concatenation operator while using php variables.

copy_directory('you/','dir/'.$name);

Updated Answer:

This could be big debate what to use. It's everyone's own opinion. But people say we should avoid complexity of double quotes. Double quotes have memory save issues. It doesn't matter for small values. So I thought it's good practice to use concatenation operator while using php variables.

Upvotes: 2

siberiantiger
siberiantiger

Reputation: 305

Use double quotes instead of single quotes;

$name = "Peter"; copy_directory('you/',"dir/$name"); 

Or alternatively, concatenate the variable;

$name = "Peter"; copy_directory('you/','dir/' . $name); 

Upvotes: 3

Jason MacLean
Jason MacLean

Reputation: 513

You'll need to use double quotes in order for the variable to be interpreted as Peter

copy_directory('you/',"dir/$name");

Upvotes: 5

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15359

You need to use double quotes if you want to expand variables within a string.

$name = "Peter";
copy_directory('you/',"dir/$name");

Or, alternately, concatenate the variable onto the string:

copy_directory('you/','dir/' . $name);

Upvotes: 4

Related Questions