Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain this array declaration in PHP -> $a{0} = "value"

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?

like image 294
Kanishka Panamaldeniya Avatar asked Mar 05 '14 07:03

Kanishka Panamaldeniya


2 Answers

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

like image 56
Shankar Narayana Damodaran Avatar answered Sep 28 '22 19:09

Shankar Narayana Damodaran


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.

like image 23
Nathan Dawson Avatar answered Sep 28 '22 18:09

Nathan Dawson