Hi all,

In all my time with PHP I have only ever seen one way of adding a variable onto the end of the string:

$string = "hello" . $variable;

However, recently I came across another method, which was used in the context of constructing a mySQL query. Can someone explain the difference? It seems like a much easier way to achieve the same result:

$sql = "SELECT * FROM {$table}";

When you use double quotes you can include the variable and this will be expanded to the associated value. The curly braces {$var} are used to write complex expressions when the variable is: an index array, an object or an anonymous function.

Few examples:

# array
$str  = "Hello {$data['name']}";

# object
$str  = "Hello {$data->name}";

# anonymous function
$data = ['name' => 'James'];
$name = function($array) { return $array['name']; };
$str  = "Hello {$name($data)}";

For more information look at the complex syntax examples in the documentation:

Member Avatar

diafol

Just to add to cereal's input - you can also use HEREDOC:

$string = <<<STR
This is my $table. I can include a property: $myObject->myProperty.
But I can also include an object array property element like {$obj->prop[6]}.
STR;

echo $str;

I find this useful if you have a large section of text with a lot of property values to include. For simple cases though, just use the concatenation or include inside double quotes. Just remember to "brace" your properties and array elements if you do the latter (as mentioned by cereal).

Thanks for your responses, that's really helpful. But how come the variable I used in my example is a string, not an array or an object?

Member Avatar

diafol

Thanks for your responses, that's really helpful. But how come the variable I used in my example is a string, not an array or an object?

Well, actually we don't know this for sure, as $variable could be a simple variable (integer, float, string, etc) or an array or an object. However, you did say in your opening post that $variable was concatenated to the end of a string. If it is a simple var, then you can concatenate it. If it is an array or an object, then you can't - you can however concatenate an array element or an object property (or the result of a function if it is allowed).