Should I use curly brackets or concatenate variables within strings?
All of the following does the same if you look at the output.
$greeting = "Welcome, " . $name . "!";
$greeting = 'Welcome, ' . $name . '!';
$greeting = "Welcome, $name!";
$greeting = "Welcome, {$name}!";
You should not be using option 1, use option 2 instead. Both option 3 and 4 are the same. For a simple variable, braces are optional. But if you are using array elements, you must use braces; e.g.: $greeting = "Welcome, {$user['name']}!";
. Therefore as a standard, braces are used if variable interpolation is used, instead of concatenation.
But if characters such as tab (\t
), new-line (\n
) are used, they must be within double quotations.
Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate. Therefore decide depending on how many variables among other characters.
Concatenating a string and a variable within curly braces
You can store those functions in an array and can use that array in onClick
,
render() {
const fns = [this.social0, this.social1, this.social2, this.social3]
return (
<div>
{buttons.map((btn, key) => {
return (
<button onClick={fns[key]} key={key}>
{btn}
</button>
)
})}
</div>
)
}
Demo
What does ${} (dollar sign and curly braces) mean in a string in JavaScript?
You're talking about template literals.
They allow for both multiline strings and string interpolation.
Multiline strings:
console.log(`foo
bar`);
// foo
// bar
Is it wrong to use curly braces after the dollar sign inside strings
${...}
is a syntax for another purpose. It is used to indirectly reference variable names. Without string interpolation, literal names in curly braces or brackets are written as string literals, thus enclosed in quotes. However, inside interpolation quotes are not used outside curly braces:
$bar = 'baz';
echo $bar , PHP_EOL;
echo ${'bar'} , PHP_EOL;
$arr = ['a' => 1, 'b' => ['x' => 'The X marks the point.']];
echo $arr['a'] , PHP_EOL;
// interpolation:
echo "$arr[a] / {$arr['a']}" , PHP_EOL;
Instead of literals you can use functions as well:
function foo(){return "bar";}
// Here we use the function return value as variable name.
// We need braces since without them the variable `$foo` would be expected
// to contain a callable
echo ${foo()} , PHP_EOL;
When interpolating, you need to enclose into curly braces only when the expression otherwise would be ambiguous:
echo "$arr[b][x]", PHP_EOL; // "Array[x]"
echo "{$arr['b']['x']}", PHP_EOL; // "The X marks the point."
Now we understand that ${...}
is a simple interpolation "without braces" similar to "$arr[a]"
since the curly braces are just for indirect varable name referencing. We can enclose this into curly braces nevertheless.
Interpolated function call forming the variable name:
echo "${foo()} / {${foo()}}", PHP_EOL;
// "baz / baz" since foo() returns 'bar' and $bar contains 'baz'.
Again, "${bar}"
is equivalent to ${'bar'}
, in curly braces: "{${'bar'}}"
.
As asked in comments,
there is another curly brace syntax to reference array keys.
$someIdentifier{'key'}
This is just an alternative syntax to PHP's common array syntax $array['key']
.
In opposit to the latter, on indirect variable name references the curly braces follow immediately after the $
or the object member operator ->
. To make it even more cryptic we can combine both:
$bar['baz'] = 'array item';
echo ${'ba' . 'r'}{'ba'.'z'};
which is equivalent to echo $bar['baz'];
Really weird in PHP's string interpolation: "${bar}"
is valid and "${'bar'}"
as well but not "$array['key']"
, "$array[key]"
is valid instead, but both, "$array{key}"
and "$array{'key'}"
, do not work at all.
Conclusion
It should be made a habit to use braced interpolation syntax all the time. Braced array key syntax should be avoided at all.
Always use:
"{$varname} {$array['key']} {${funcname().'_array'}['key']}"
See also PHP documentation:
- Complex curly syntax
(to distinguish from)
Variable variables (also known as indirect variable name referencing)
Accessing array elements
Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).
Is using curly braces in variables good practice in php
Using curly brace syntax is slightly slower. Consider the following test:
<?php
$array = array('key'=>'val');
$start1 = microtime(TRUE);
for ($i = 0; $i < 100000; $i++) {
$str = "<tag>{$array['key']}</tag>";
}
$end1 = microtime(TRUE);
$result1 = $end1 - $start1;
$start2 = microtime(TRUE);
for ($j = 0; $j < 100000; $j++) {
$str = "<tag>".$array['key']."</tag>";
}
$end2 = microtime(TRUE);
$result2 = $end2 - $start2;
$start3 = microtime(TRUE);
for ($k = 0; $k < 100000; $k++) {
$str = '<tag>'.$array['key'].'</tag>';
}
$end3 = microtime(TRUE);
$result3 = $end3 - $start3;
echo "1: $result1\n2: $result2\n3: $result3\n";
?>
On my PHP/5.2.19-win32 system, the first test (with curly braces) is slightly slower (~7%). However, the difference is so small as to be not worth worrying about, and I would say do whatever you are most comfortable with.
Slightly counter-intuitively, the second test is consistently faster than the third (~2%) - double quotes are faster than single quotes - and I would have expected it to be the other way around.
How concatenate more values inside a variable with values inside braces(Curly brackets)
You can use Object.assign
to "merge" two objects. For example:
var obj1 = {a: 1, b: 2};
var obj2 = {c: 3};
var obj3 = Object.assign({}, obj1, obj2);
console.log(obj3);
Matlab concatenate variable string without curly braces
subs
is a cell array. If you index it using ()
notation, you will also get a cell array.
a = {'1', '2', '3'};
class(a(1))
% cell
To get the string inside the cell array you need to use {}
notation to index into it.
class(a{1})
% char
When you use strcat
with cell arrays, the result will be a cell array. When you use it with strings, the resut will be a string. So if we switch out (k)
with {k}
we get what you expect.
for k = 1:numel(subs)
subject = subs{k};
files_in(k).test = strcat('/home/data/ind/', subject, '/test_ind_', subject, '.mat');
end
A few side notes:
Don't use
i
as a variable.i
andj
are used in MATLAB to indicatesqrt(-1)
.It is recommended to use
fullfile
to construct file paths rather thanstrcat
.
Related Topics
PHP 5 Strpos() Difference Between Returning 0 and False
Upload Multiple Files With PHP and Jquery
Get the First N Elements of an Array
Regular Expression Pattern to Match Url With or Without Http://Www
Elegant Way to Get the Count of Months Between Two Dates
Sort and Display Directory List Alphabetically Using Opendir() in PHP
How to Prevent the "Confirm Form Resubmission" Dialog
PHP, MySQL Error: Column Count Doesn't Match Value Count At Row 1
Parentheses Altering Semantics of Function Call Result
MySQL_Fetch_Array, MySQL_Fetch_Assoc, MySQL_Fetch_Object
PHP Sessions Timing Out Too Quickly
Get Difference Between Associative Rows of Two 2-Dimensional Arrays
Preserve Key Order (Stable Sort) When Sorting With PHP'S Uasort