php array short syntax
Shorthand syntax for PHP arrays
Is this valid PHP syntax or just a shorthand for the documentation? Does anybody have the link to a help page describing this notation?
If you have a look at the code examples in the Unpacking nested arrays with list() section on the foreach help page you will see this possibly new notation, however I can’t seem to find any help for this.
4 Answers 4
The new syntax [] was added in PHP 5.4.0. Check out the documentation on arrays
The page you reference is saying that unpacking the array using list() is new in PHP 5.5, not the short array syntax itself, which was added in PHP 5.4.
PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.
That is no more than an array of arrays. These two snippets are identical:
This is documented in the PHP manual page for Arrays and has been possible since PHP 5.4.
Why don’t you just test the code? I’m using PHP Version 5.4.7 and it is already valid code. Example:
Not the answer you’re looking for? Browse other questions tagged php syntax or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
PHP RFC: Square bracket syntax for array destructuring assignment
Background
Arrays can be constructed in PHP syntax using one of two syntax forms. The first of these, introduced in PHP 3, resembles a function call, where a series of comma-separated values (and optionally keys) is placed between array ( and ) :
The second syntax form, the so-called short array syntax introduced in PHP 5.4, is a more concise form that replaces array ( and ) with [ and ] :
Beyond being more concise, this second syntax has the benefit of not resembling a function call (preventing misunderstandings from new users), and being familiar to users of other languages like JavaScript, which use similar syntax for constructing arrays.
Similar to the array ( ) syntax for constructing arrays, PHP has had a syntax form for assigning to variables from array elements (“destructuring”) since PHP 3, where a series of comma-separated variables are placed between list ( and ) :
Proposal
Importantly, this syntax for destructuring an array means there is now symmetry between array construction and destructuring, which should make it clearer what the function of the syntax is:
This symmetry between construction and destructuring is a feature in some other languages. The following code, for example, is valid ECMAScript 6, and would behave identically in PHP:
Details
The list ( ) syntax is not only permitted on the left-hand side of an assignment operation, but also as variable in a foreach loop. The new [ ] syntax for destructuring would likewise be permitted here:
Aside from this restriction, assignment with [ ] on the left-hand side behaves identically to list ( ) in all respects.
Backward Incompatible Changes
Proposed PHP Version(s)
This is proposed for the next minor or major version of PHP, whichever comes first. At the time of writing, this would be PHP 7.1.
array
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Create an array
Description
Creates an array. Read the section on the array type for more information on what an array is.
Parameters
Syntax «index => values», separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.
Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.
Return Values
Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.
Examples
The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.
Example #1 array() example
Example #2 Automatic index with array()
The above example will output:
Note that index ‘3’ is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.
This example creates a 1-based array.
Example #3 1-based index with array()
The above example will output:
As in Perl, you can access a value from the array inside double quotes. However, with PHP you’ll need to enclose your array between curly braces.
Example #4 Accessing an array inside double quotes
Notes
array() is a language construct used to represent literal arrays, and not a regular function.
See Also
User Contributed Notes 38 notes
As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.
So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.
Here’s a further example:
$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);
$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);
$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);
Php array short syntax
PHP 5.4 Short Array Syntax Converter
Command-line script to convert and revert PHP’s array() syntax to PHP 5.4’s short array syntax [] using PHP’s built-in tokenizer.
By relying on the PHP tokenizer, nothing but the array syntax itself will be altered. The script was successfully tested against code bases with more than 5.000 PHP files.
Run the script with the path of the PHP file you wish to convert as argument. This will print the converted source code to STDOUT.
If you want the script to process PHP files with short open tags ( ) as well, you need to make sure that the short_open_tag setting is enabled in your php.ini file.
In case of any error, an error message is written to STDERR and the script exits with a return code of 1.
Use find to convert a whole directory recursively (on Linux/Mac):
Or on Windows (thanks to John Jablonski for suggesting):
In case you don’t trust the script yet, you can even perform a syntax check after conversion:
Reverting has not yet been thoroughly tested, so use with extreme percaution!
Since there is no specific token for the short array syntax, it assumes every «[» is an aray and relies on checking the previous token for a variable, object property, function return «)», nested array «]» and variable reference «>».
Thanks to Lebenslauf.com (German CV editor) for sponsoring the development.
About
Command-line script to convert PHP’s array() syntax to PHP 5.4’s short array syntax []
Массивы
Объяснение этих структур данных выходит за рамки данного справочного руководства, но вы найдете как минимум один пример по каждой из них. За дополнительной информацией вы можете обратиться к соответствующей литературе по этой обширной теме.
Синтаксис
Определение при помощи array()
Запятая после последнего элемента массива необязательна и может быть опущена. Обычно это делается для однострочных массивов, т.е. array(1, 2) предпочтительней array(1, 2, ). Для многострочных массивов с другой стороны обычно используется завершающая запятая, так как позволяет легче добавлять новые элементы в конец массива.
Начиная с PHP 5.4 возможно использовать короткий синтаксис определения массивов, который заменяет языковую конструкцию array() на [].
Пример #1 Простой массив
Если несколько элементов в объявлении массива используют одинаковый ключ, то только последний будет использоваться, а все другие будут перезаписаны.
Пример #2 Пример преобразования типов и перезаписи элементов
Результат выполнения данного примера:
Так как все ключи в вышеприведенном примере преобразуются к 1, значение будет перезаписано на каждый новый элемент и останется только последнее присвоенное значение «d».
Массивы в PHP могут содержать ключи типов integer и string одновременно, так как PHP не делает различия между индексированными и ассоциативными массивами.
Пример #3 Смешанные ключи типов integer и string
Результат выполнения данного примера:
Пример #4 Индексированные массивы без ключа
Результат выполнения данного примера:
Возможно указать ключ только для некоторых элементов и пропустить для других:
Пример #5 Ключи для некоторых элементов
Результат выполнения данного примера:
Как вы видите последнее значение «d» было присвоено ключу 7. Это произошло потому, что самое большое значение ключа целого типа перед этим было 6.
Доступ к элементам массива с помощью квадратных скобок
Доступ к элементам массива может быть осуществлен с помощью синтаксиса arrayphp array short syntax.
Пример #6 Доступ к элементам массива
Результат выполнения данного примера:
Для доступа к элементам массива могут использоваться как квадратные, так и фигурные скобки (например, $array[42] и $array означают одно и то же в вышеприведенном примере).
С PHP 5.4 стало возможным прямое разыменование массива, возвращаемого в качестве результата вызова функции или метода. Раньше приходилось использовать временные переменные.
С PHP 5.5 стало возможным прямое разыменование элементов у литерала массива.
Пример #7 Разыменование массива
// в PHP 5.4
$secondElement = getArray ()[ 1 ];
Создание/модификация с помощью синтаксиса квадратных скобок
Существующий массив может быть изменен явной установкой значений в нем.
Это выполняется присвоением значений массиву array с указанием в скобках ключа. Кроме того, вы можете опустить ключ. В этом случае добавьте к имени переменной пустую пару скобок ([]).
$arr [ «x» ] = 42 ; // Это добавляет к массиву новый
// элемент с ключом «x»
Как уже говорилось выше, если ключ не был указан, то будет взят максимальный из существующих целочисленных ( integer ) индексов, и новым ключом будет это максимальное значение (в крайнем случае 0) плюс 1. Если целочисленных индексов еще нет, то ключом будет 0 (ноль).
Учтите, что максимальное целое значение ключа не обязательно существует в массиве в данный момент. Оно могло просто существовать в массиве какое-то время, с тех пор как он был переиндексирован в последний раз. Следующий пример это иллюстрирует:
Результат выполнения данного примера:
Полезные функции
Для работы с массивами существует достаточное количество полезных функций. Смотрите раздел функции для работы с массивами.
Управляющая конструкция foreach существует специально для массивов. Она предоставляет возможность легко пройтись по массиву.
Что можно и нельзя делать с массивами
Почему $foo[bar] неверно?
Всегда заключайте в кавычки строковый литерал в индексе ассоциативного массива. К примеру, пишите $foo[‘bar’], а не $foo[bar]. Но почему? Часто в старых скриптах можно встретить следующий синтаксис:
Замечание: Это не означает, что нужно всегда заключать ключ в кавычки. Нет необходимости заключать в кавычки константы или переменные, поскольку это помешает PHP обрабатывать их.
Результат выполнения данного примера:
Дополнительные примеры, демонстрирующие этот факт:
// Показываем все ошибки
error_reporting ( E_ALL );
Если вы переведете error_reporting в режим отображения ошибок уровня E_NOTICE (например, такой как E_ALL ), вы сразу увидите эти ошибки. По умолчанию error_reporting установлена их не отображать.
Как указано в разделе синтаксис, внутри квадратных скобок (‘[‘ и ‘]‘) должно быть выражение. Это означает, что можно писать вот так:
Это пример использования возвращаемого функцией значения в качестве индекса массива. PHP известны также и константы:
поскольку E_ERROR соответствует 1, и т.д.
Так что же в этом плохого?
Когда-нибудь в будущем, команда разработчиков PHP, возможно, пожелает добавить еще одну константу или ключевое слово, либо константа из другого кода может вмешаться и тогда у вас могут возникнуть проблемы. Например, вы уже не можете использовать таким образом слова empty и default, поскольку они являются зарезервированными ключевыми словами.
Преобразование в массив
Если вы преобразуете в массив объект ( object ), вы получите в качестве элементов массива свойства (переменные-члены) этого объекта. Ключами будут имена переменных-членов, с некоторыми примечательными исключениями: целочисленные свойства станут недоступны; к закрытым полям класса (private) спереди будет дописано имя класса; к защищенным полям класса (protected) спереди будет добавлен символ ‘*’. Эти добавленные значения с обоих сторон также имеют нулевые байты. Это может вызвать несколько неожиданное поведение:
var_dump ((array) new B ());
?>
Вышеприведенный код покажет 2 ключа с именем ‘AA’, хотя один из них на самом деле имеет имя ‘\0A\0A’.
Сравнение
Массивы можно сравнивать при помощи функции array_diff() и операторов массивов.
Примеры
The array type in PHP is very versatile. Here are some examples: Тип массив в PHP является очень гибким, вот несколько примеров:
Пример #8 Использование array()
// пустой массив
$empty = array();
?>
Пример #9 Коллекция
Результат выполнения данного примера:
Изменение значений массива напрямую стало возможным с версии PHP 5 путем передачи их по ссылке. До этого необходим следующий обходной прием:
Пример #10 Изменение элемента в цикле
Результат выполнения данного примера:
Следующий пример создает массив, начинающийся с единицы.
Пример #11 Индекс, начинающийся с единицы
Результат выполнения данного примера:
Пример #12 Заполнение массива
Пример #13 Сортировка массива
Поскольку значение массива может быть чем угодно, им также может быть другой массив. Таким образом вы можете создавать рекурсивные и многомерные массивы.
Пример #14 Рекурсивные и многомерные массивы
// Создаст новый многомерный массив
$juices [ «apple» ][ «green» ] = «good» ;
?>
Обратите внимание, что при присваивании массива всегда происходит копирование значения. Чтобы скопировать массив по ссылке, вам нужно использовать оператор ссылки.