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?
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 [].
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.
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.
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner.
"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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With