数组的简写:是否有像{}或[]这样的字面语法?

Jam*_*mes 81 php arrays syntax

PHP中数组表示法的简写是什么?

我试图使用(不起作用):

$list = {};
Run Code Online (Sandbox Code Playgroud)

如果您提供有关PHP的其他缩写的一些信息的链接,那将是完美的.

Ali*_*aru 129

更新:
从PHP 5.4.0 开始,引入了用于声明数组的缩写语法:

$list = [];
Run Code Online (Sandbox Code Playgroud)

上一个答案:

There isn't. Only $list = array(); But you can just start adding elements.

<?php
$list[] = 1;
$list['myKey'] = 2;
$list[42] = 3;
Run Code Online (Sandbox Code Playgroud)

It's perfectly OK as far as PHP is concerned. You won't even get a E_NOTICE for undefined variables.

E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array.

As for shorthand methods, there are lots scattered all over. If you want to find them just read The Manual.

Some examples, just for your amusement:

  1. $arr[] shorthand for array_push.
  2. The foreach construct
  3. echo $string1, $string2, $string3;
  4. Array concatenation with +
  5. The existence of elseif
  6. Variable embedding in strings, $name = 'Jack'; echo "Hello $name";

  • PHP就像这样偷偷摸摸. (6认同)
  • $ results [] = $ row; 实际上比array_push快得多($ results,$ row) (2认同)

Age*_*nce 44

是的,它存在!!

从另一个Stack Overflow问题中提取:

数组的缩写语法已被重新讨论,接受,现在正在使用PHP 5.4发布

用法:

$list = [];
Run Code Online (Sandbox Code Playgroud)

参考:PHP 5.4数组短手

  • 对于也犯过这个错误的人,请在键和值之间使用 `=&gt;` 而不是 `:`! (2认同)

Die*_*itz 29

也可以在[]中定义内容,如下所示:

  $array = ['vaue1', 'value2', 'key3'=>['value3', 'value4']];
Run Code Online (Sandbox Code Playgroud)

这只适用于php5.4及以上版本.

  • 我认为最好编写 5.4 及更高版本(在 5.6 中它有效)。请注意,这是将数组声明为类常量的唯一有效方法(例如 const x = ["a", "b"];),因为 const x=array(....) 不起作用 (2认同)