Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP curly braces in array notation

Tags:

arrays

php

braces

I'd just come across a very weird bit of php code:

$oink{'pig'} = 1; var_dump($oink);  $oink{'pig'} = '123123'; echo $oink{'pig'}; /* => 123123 */ echo $oink['pig']; /* => 123123 */ 

It works like an array, but nowhere mentioned in the manual. What is this?

like image 528
Jauzsika Avatar asked Nov 11 '11 09:11

Jauzsika


People also ask

What are the curly brackets {{ }} used for?

Curly brackets are commonly used in programming languages such as C, Java, Perl, and PHP to enclose groups of statements or blocks of code.

What do curly brackets mean in PHP?

Introduction. PHP allows both square brackets and curly braces to be used interchangeably for accessing array elements and string offsets. For example: $array = [1, 2]; echo $array[1]; // prints 2 echo $array{1}; // also prints 2 $string = "foo"; echo $string[0]; // prints "f" echo $string{0}; // also prints "f"

What is curly brace notation?

The symbols "{" and "} are called braces, curly braces or curly brackets. Braces are used as bare delimiters when there are nested parentheses, in much the same way as square brackets. Braces are used in the list notation for sets. They are also used in setbuilder notation..

What do brackets mean in PHP?

In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array. Ordered Arrays.


1 Answers

It is mentioned in the manual. {} is just an alternative syntax to [] § Accessing array elements with square bracket syntax. This method is deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Note:

Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

The same goes the strings § String access and modification by character :

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. [...]

Note: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

like image 137
Pacerier Avatar answered Sep 28 '22 10:09

Pacerier