Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

As i recently learned $myArray[$index] in PHP is equivalent to $myArray{$index}.

This mentioned on PHP docs. Also i found small discussion here: PHP curly braces in array notation.

PHP-FIG does not contains any recommendations about which way is preferable.

So, my question is -- it's just a matter of taste or may be some objective reasons to use one or the other syntax?

like image 500
oakymax Avatar asked Jul 16 '16 20:07

oakymax


People also ask

What is the difference between array () and [] in PHP?

Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].

What are the different types of array in PHP?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What are square brackets used for 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.

What does curly braces mean in PHP?

As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner.


1 Answers

"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)"
like image 197
RomanPerekhrest Avatar answered Oct 11 '22 16:10

RomanPerekhrest