Hi i am using PHP for couple of years ,
these are the ways in PHP that i know to declare an array
$arr = array();
$arr = array(1,2);
$arr[0] = 1;
$arr[] = 1;
In an example I saw this syntax and I ran the code and it was valid:
$a{0} = "value";
but the following code didn't run:
$a{} = "value";
It gave:
Parse error: syntax error, unexpected '}'
How to explain this?
From the PHP docs:
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 ).
{ }
is not just for accessing, you can even append elements to the array provided you pass the key !
$arr{34} = 'some data'; // <--- Valid
OUTPUT:
Array
(
[34] => some data
)
but
$arr{} = 'some data';// <--- This is not a valid and it throws an error.
The only difference between { }
and [ ]
is that you need to pass the key for the former. Else, it will throw an error: PHP Parse error: syntax error, unexpected '}'
.
It's just the same as square brackets but closer to Perl syntax.
http://uk1.php.net/manual/en/language.types.array.php#99015
You're only able to access existing elements this way. As you've already pointed out $a{} = 1;
won't work.
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