从PHP数组读取时[]是什么意思? [英] What does [] mean when reading from a PHP array?

查看:77
本文介绍了从PHP数组读取时[]是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为PHP编写解析器,并且在弄乱一些第三方代码的同时,遇到了关于[]运算符的怪异案例.

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;

将在数组$ 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

尽管使用&,PHP完全不会抱怨.表达式的含义是什么

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

& $a[];

?

推荐答案

语法的含义是使用对$ a []的引用"或对最新创建的数组元素的引用.

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);

产生:

Array
(
    [0] => a
    [1] => b
)
Array
(
    [0] => a
    [1] => b
    [2] => 
)
Array
(
    [0] => a
    [1] => b
    [2] => c
)

这篇关于从PHP数组读取时[]是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆