6

I've been writing a parser for PHP and while messing around with some third-party code, I run into a weird case regarding the [] operator.

Normally, [] is used without a key on the left side of an assignment meaning "add as the last element".

$a = array();
$a[] = 1;

will add 1 in the end of array $a.

In the aforementioned code though, I saw a line like this:

$r =& $a[];

When I tried to remove the &, I got a rather expected fatal error:

Fatal error: Cannot use [] for reading

With the & though, PHP does not complain at all. What is the meaning of the expression

& $a[];

?

2 Answers 2

12

The syntax means "use a reference to $a[]" or a reference to the newest created array element.

<?php
$a=array( );
$a[] = "a";
$a[] = "b";

print_r($a);

$r =& $a[];

print_r($a);

$r = "c";

print_r($a);

produces:

Array
(
    [0] => a
    [1] => b
)
Array
(
    [0] => a
    [1] => b
    [2] => 
)
Array
(
    [0] => a
    [1] => b
    [2] => c
)
Sign up to request clarification or add additional context in comments.

1 Comment

Now that we know what it means, let's all promise never to use it.
1

My guess is that it adds an empty element to the array and gives $r a reference to that array element. Are you sure $a is supposed to be an array? It could also be trying to access a character of a string using the [] syntax, in which case I have no idea how that would work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.