PHP Curly Braces in Array Notation

PHP arrays -- square brackets vs curly braces ($array[$i] vs $array{$i})

"Square bracket notation" for array elements would be more unified and acceptable.
"Curly bracket notation" will work in expressions but not in variable interpolation when dealing with accessing of an array element.
Consider the following example:

$myArray = [1,2];
$index = 1;

echo "value at index $index is $myArray[$index]"; // outputs "value at index 1 is 2"

echo "value at index $index is $myArray{$index}"; // will throw "Notice: Array to string conversion"

var_dump($myArray{$index}); // outputs "int(2)"

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'].

Curly braces inside PHP array

PHP >=5.4

[
'title' => 'Property',
'image' => '1-1-thmb.png',
'type' => 'For Sale',
'price' => '$price',
'address' => '$address',
'bedrooms' => '$bedrooms',
'bathrooms' => '$maxguests',
'area' => '$area',
'position' => [
'lat' => '$lat',
'lng' => '$lng'
],
'markerIcon' => 'marker-green.png'
]

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/

Array-like statement with curly brackets - what is the purpose?

That's not an array syntax. It's for accessing single characters from strings only. The index must be numeric.

 $str{1} == $str[1]

It's briefly mentioned here in the info box: http://www.php.net/manual/en/language.types.string.php#language.types.string.substr

Also, it's officially declared deprecated. It has been on and off supposed deprecation in the manual, but is still very valid, if uncommon, syntax.


The & 0x1F is a bit-wise AND. In this case it limits the decimal values to 0 till 31.

What does ${ } mean in PHP syntax?

${ } (dollar sign curly bracket) is known as Simple syntax.

It provides a way to embed a variable, an array value, or an object
property in a string with a minimum of effort.

If a dollar sign ($) is encountered, the parser will greedily take as
many tokens as possible to form a valid variable name. Enclose the
variable name in curly braces to explicitly specify the end of the
name.

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .
He drank some juice made of apples.

PHP curly brace syntax for member variable

Curly braces are used to explicitly specify the end of a variable name. For example:

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

So, your case is really a combination of two special cases. You're allowed to access class variables using curly braces and like so:

$class->{'variable_name'} // Same as $class->variable_name
$class->{'variable' . '_name'} // Dynamic values are also allowed

And in your case, you're just surrounding them with the curly brace syntax.

See the PHP manual, "complex (curly) syntax."

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";


Related Topics



Leave a reply



Submit