Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Dan Neumann
PLUS
Dan Neumann
Courses Plus Student 10,318 Points

When do I need to concatenate in php

I don't understand why this code works:

<?php

function hello($name) {
  echo "Hello, $name";
}

hello('Hampton');
?>

I thought I had to concatenate every time there was a combination of strings and php elements ($name in this case).

2 Answers

Hey Dan,

Concatenation does actually have to be done in certain circumstances such as inserting carriage returns/new lines or if you were calling two functions and using the results in some kind of output. See below for an example of this. There are more examples but these are common ones.

In this case, though, since we used double quotes for the string, you can use variables inside of the string with no need for concatenation.

Check out this example where concatenation is necessary:

<?php
function hello ($name) {
  return "Hello, $name";
}

function goodbye ($name) {
  return "goodbye, $name";
}

echo hello('Marcus') . ", and ". goodbye('Bobbert'). ".";
//outputs to the screen:
//Hello, Marcus, and goodbye, Bobbert.
?>
Dan Neumann
PLUS
Dan Neumann
Courses Plus Student 10,318 Points

Thanks - That's the first explanation I've heard for this. Is there a list of rules or a video where the difference is defined? I haven't heard any explanation of this in the php videos I have watched yet.

As you progress further into learning PHP, you'll know when you need to use it, I promise. You'll probably end up using concatenation more often than inserting variable names into strings because concatenation is a very useful tool.

When in doubt, Dan, try concatenation! :) If you have any more questions, don't hesitate to come on back to the forums. Happy Coding!