Curly Braces in String in PHP

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax


This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }. Since { can not be escaped, this syntax
will only be recognised when the $ immediately follows the {. Use
{\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

When to wrap curly braces around a variable

What are PHP curly braces:

You know that a string can be specified in four different ways. Two of these ways are – double quote("") and heredoc syntax. You can define a variable in those 2 types of strings and PHP interpreter will parse or interpret that variable too, within the strings.

Now, there are two ways you can define a variable in a string – simple syntax which is the most used method of defining variables inside a string and complex syntax which uses curly braces to define variables.

Curly braces syntax:

To use a variable with curly braces is very easy. Just wrap the variable with { and } like:

{$variable_name}

Note: There must not be any gap between { and $. Else, PHP interpreter won't consider the string after $ as a variable.

Curly braces example:

<?php
$lang = "PHP";
echo "You are learning to use curly braces in {$lang}.";
?>

Output:

You are learning to use curly braces in PHP.

When to use curly braces:

When you are defining a variable inside a string, PHP might mix up the variable with other characters if using simple syntax to define a variable and this will produce an error. See the example below:

<?php
$var = "way";
echo "Two $vars to defining variable in a string.";
?>

Output:

Notice: Undefined variable: vars …

In the above example, PHP's interpreter considers $vars a variable, but, the variable is $var. To separate a variable name and the other characters inside a string, you can use curly braces. Now, see the above example using curly braces-

<?php
$var = "way";
echo "Two {$var}s to define a variable in a string.";
?>

Output:

Two ways to define a variable in a string.

Source: http://schoolsofweb.com/php-curly-braces-how-and-when-to-use-it/

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).

Adding Curly Braces on Array of String PHP

array_count_values() returns a list of the values and the number of times they occur, so just using array_push() will add this entire array as 1 item and give you the results your getting.

Instead, you can add the results one at a time to the $temp array and get the results your after...

$temp = [];
$res = array_count_values(array_column($query, 'status'));
foreach ( $res as $key=>$item ) {
$temp[] = [$key => $item];
}
print_r(json_encode($temp));

php curly braces replace values

If you really want to use curly braces, try this. All replaces will be done automatically, just from matched variable names.

$CH_NAME = "John";
$URL_NAME = "http://xxxx";
$beforeStr = "YOUR NAME {CH_NAME} {URL_NAME}";

preg_match_all('/{(\w+)}/', $beforeStr, $matches);
$afterStr = $beforeStr;
foreach ($matches[0] as $index => $var_name) {
if (isset(${$matches[1][$index]})) {
$afterStr = str_replace($var_name, ${$matches[1][$index]}, $afterStr);
}
}

echo $afterStr;

Curly Braces Notation in PHP

Curly braces are used to denote string or variable interpolation in PHP. It allows you to create 'variable functions', which can allow you to call a function without explicitly knowing what it actually is.

Using this, you can create a property on an object almost like you would an array:

$property_name = 'foo';
$object->{$property_name} = 'bar';
// same as $object->foo = 'bar';

Or you can call one of a set of methods, if you have some sort of REST API class:

$allowed_methods = ('get', 'post', 'put', 'delete');
$method = strtolower($_SERVER['REQUEST_METHOD']); // eg, 'POST'

if (in_array($method, $allowed_methods)) {
return $this->{$method}();
// return $this->post();
}

It's also used in strings to more easily identify interpolation, if you want to:

$hello = 'Hello';
$result = "{$hello} world";

Of course these are simplifications. The purpose of your example code is to run one of a number of functions depending on the value of $result['code'].

Replace all spaces in string inside curly braces

You may use \G bases regex for this:

$str = 'x{Test test} test test x{Test test test } test {Test test}';

$repl = preg_replace('/(?:x{|(?<!^)\G)[^\s}]*\K\s+(?!})/', '_', $str);
//=> x{Test_test} test test x{Test_test_test } test {Test test}

RegEx Demo

RegEx Details:

  • \G asserts position at the end of the previous match or the start of the string for the first match.
  • (?:x{|(?<!^)\G): Matches x{ or end of previous match
  • \K: Reset current match info
  • \s+: Match 1+ whitespace
  • (?!}): Assert we don't have an } immediate ahead

PHP replace string between curly brackets with array element value

You can use preg_replace_callback and use the capturing group ([^}]+) to find an index in the array $text:

$repl = preg_replace_callback('/{{([^}]+)}}/', function ($m) use ($text) {
return $text[$m[1]]; }, $body);
//=> This is a body of really cool text from a book.

The use ($text) statement passes the reference of $text to the anonymous function.

How do you insert a php function inside of curly brackets and double quotes?

You can try this way :

$mktime = mktime();
echo "the unix time is {$mktime}";

Also you can concatenate with dots :

echo "the unix time is {" . mktime() . "}";

PHP curly brace syntax for calling methods using string

It's part of variable functions. When using variable variables or variable functions, you can replace the variable with any expression that returns a string by wrapping on braces. So you can do:

$var = 'SayHi';
$player->$var();

or you can do it in one step with:

$player->{'SayHi'}();

The syntax with braces is shown in the documentation of variable variables. The example there is for a variable class property, but the same syntax is used for class methods.



Related Topics



Leave a reply



Submit