简体   繁体   English

创建多维php数组而无需声明

[英]Creating multidimensional php arrays without declaring

I've noticed this and am not sure how to work with it. 我注意到了这一点,并且不确定如何使用它。

Basically, it seems PHP magically creates sub-arrays if you use them? 基本上,如果您使用子数组,PHP似乎会神奇地创建子数组?

// $moo is not defined
$moo['agagag']['sdfsdf'][] = 4654645;

// no E_NOTICE or anything, it creates the array

// array(
//   'agagag' => array(
//     'sdfsdf' => array(
//       0 => 4654645
//     )
//   )
// )

Is this behavior documented anywhere? 此行为记录在任何地方吗? Is it safe to use? 使用安全吗?

(I'm used to creating each level manually, this feels really weird) (我习惯于手动创建每个级别,这感觉很奇怪)

Yes, this behaviour is expected and also documented in the manual : 是的,此行为是预期的,并且也记录在手册中

 $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type 

If $arr doesn't exist yet, it will be created , so this is also an alternative way to create an array . 如果$ arr还不存在,它将被创建 ,因此这也是创建array另一种方法 This practice is however discouraged because if $arr already contains some value (eg string from request variable) then this value will stay in the place and [] may actually stand for string access operator. 但是不建议这样做,因为如果$ arr已经包含某个值(例如,来自请求变量的字符串),则该值将保留在该位置,并且[]实际上代表字符串访问运算符。 It is always better to initialize variable by a direct assignment. 最好总是通过直接赋值来初始化变量。

It is save and you can use it but i prefer the following at declaration: 它已保存,您可以使用它,但是我在声明时喜欢以下内容:

$moo = array(
   'agagag' => array(
       'sdfsdf' => array(
            4654645
        )
    )
);

It is standard behaviour and there's nothing wrong with it: you can look at the full documentation here: http://php.net/manual/en/language.types.array.php (see "Creating/modifying with square bracket syntax"). 这是标准行为,没有任何问题:您可以在此处查看完整的文档: http : //php.net/manual/en/language.types.array.php (请参阅“使用方括号语法创建/修改” )。

Of course you must be aware of it in all your code and of course, if you know in advance the structure of the array, you may define it as per @Frankbeen answer, 当然,您必须在所有代码中都意识到这一点,当然,如果您事先知道数组的结构,则可以按照@Frankbeen答案定义它,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM