Масив (array) Масив в PHP - це упорядкована структура даних, яка зв'язує значення і ключі. Цей тип оптимізований для різних цілей, із ним можна працювати як із масивом, списком (вектором), хеш-таблицею (реалізація карти), словником, колекцією, стеком, чергою, і, мабуть, більше. Оскільки значення масиву можуть бути іншими масивами, також можливі дерева та багатовимірні масиви. Пояснення цих структур даних виходить за рамки цього посібника, але для кожної з них надається принаймні один приклад. Щоб отримати додаткову інформацію, перегляньте значну кількість літератури, яка існує на цю широку тему. Синтаксис Зазначення використовуючи <function>array</function> Масив (array) можна створити за допомогою мовної конструкції array. Він приймає будь-яку кількість розділених комами ключ => значення пар як параметри. array( key => value, key2 => value2, key3 => value3, ... ) Кома після останнього елемента масиву необов’язкова, її можна опустити. Зазвичай це робиться для однорядкових масивів, наприклад array(1, 2) вважається кращим, ніж array(1, 2, ). З іншого боку, для багаторядкових масивів кінцева кома зазвичай використовується, оскільки дозволяє легше додавати нові елементи в кінець. Існує короткий синтаксис масиву, який замінює array() на []. Простий масив "bar", "bar" => "foo", ); // Використання короткого синтаксису масиву $array = [ "foo" => "bar", "bar" => "foo", ]; ?> ]]> Ключ масиву (key) може бути заданий цілим числом (int) або строкою (string). Значення масиву (value) може бути будь-яким типом. Крім того, відбуватимуться наступні приведення ключів key: Рядки (string), що містять десяткові цілі числа (int) (за винятком, коли перед числом не стоїть знак +), будуть приведені до типу int. Наприклад ключ "8" фактично зберігатиметься під 8. З іншого боку, "08" не буде приведено, оскільки це недійсне десяткове ціле число. Десяткові дроби (float) також перетворюються на цілі числа (int), що означає, що дробова частина буде скорочена. Наприклад ключ 8.7 фактично зберігатиметься під 8. Логічний тип (bool) також перетворюється на ціле число (int), тобто ключ &true; фактично зберігатиметься під 1, а ключ &false; під 0. Тип null буде приведено до порожнього рядка, тобто ключ null фактично зберігатиметься під "". Масиви (array) та обʼєкти (object) не можуть бути використані як ключі. Це призведе до попередження: Illegal offset type. Якщо кілька елементів в оголошенні масиву використовують той самий ключ, буде використано лише останній, оскільки всі інші буде перезаписано. Приклад переведення типів і перезапису "a", "1" => "b", 1.5 => "c", true => "d", ); var_dump($array); ?> ]]> &example.outputs; string(1) "d" } ]]> Оскільки всі ключі у наведеному вище прикладі приведено до 1, значення буде перезаписано на кожному новому елементі, та залишиться тільки останнє присвоєне значення "d". Масиви PHP можуть містити цілочисленні (int) і строкові (string) ключі одночасно, оскільки PHP не розрізняє індексовані та асоціативні масиви. Змішані цілочисленні (<type>int</type>) і строкові (<type>string</type>) ключі "bar", "bar" => "foo", 100 => -100, -100 => 100, ); var_dump($array); ?> ]]> &example.outputs; string(3) "bar" ["bar"]=> string(3) "foo" [100]=> int(-100) [-100]=> int(100) } ]]> Ключ (key) необов'язковий. Якщо його не вказано, PHP використовуватиме приріст найбільшого раніше використаного цілого (int) ключа. Індексовані масиви без ключа ]]> &example.outputs; string(3) "foo" [1]=> string(3) "bar" [2]=> string(5) "hello" [3]=> string(5) "world" } ]]> Можна вказати ключ для одних елементів і не вказати для інших: Ключі не на всіх елементах "c", "d", ); var_dump($array); ?> ]]> &example.outputs; string(1) "a" [1]=> string(1) "b" [6]=> string(1) "c" [7]=> string(1) "d" } ]]> Як ви бачите, останньому значенню "d" було присвоєно ключ 7. Це тому, що найбільший цілий ключ до цього був 6. Приклад складного приведення типу та перезапису Цей приклад включає всі варіанти приведення типів ключів і перезапису елементів. 'a', '1' => 'b', // значення "a" буде перезаписано значенням "b" 1.5 => 'c', // значення "b" буде перезаписано значенням "c" -1 => 'd', '01' => 'e', // оскільки ключ не є цілим числом, він НЕ перезапише ключ для 1 '1.5' => 'f', // оскільки ключ не є цілим числом, він НЕ перезапише ключ для 1 true => 'g', // значення "c" буде перезаписано значенням "g" false => 'h', '' => 'i', null => 'j', // значення "i" буде перезаписано значенням "j" 'k', // значенню "k" буде присвоєно ключ 2. Це тому, що найбільший ключ цілого числа до цього був 1 2 => 'l', // значення "k" буде перезаписано значенням "l" ); var_dump($array); ?> ]]> &example.outputs; string(1) "g" [-1]=> string(1) "d" ["01"]=> string(1) "e" ["1.5"]=> string(1) "f" [0]=> string(1) "h" [""]=> string(1) "j" [2]=> string(1) "l" } ]]> Доступ до елементів масиву за допомогою синтаксису квадратних дужок Доступ до елементів масиву можна отримати за допомогою синтаксису array[key]. Доступ до елементів масиву "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?> ]]> &example.outputs; До PHP 8.0.0 квадратні та фігурні дужки могли використовуватися як взаємозамінні для доступу до елементів масиву (наприклад, $array[42] і $array{42} робили б те саме у прикладі вище). Синтаксис фігурних дужок застарів із PHP 7.4.0 і більше не підтримується з PHP 8.0.0. Розіменування масиву ]]> Спроба отримати доступ до ключа масиву, який не було визначено, це теж саме, як доступ до будь-якої іншої невизначеної змінної: буде видано помилку рівня E_WARNING (рівень E_NOTICE до PHP 8.0.0), і результат буде &null;. Розіменування масиву скалярного значення, яке не є рядком (string), дає &null;. До PHP 7.4.0 це не видавало повідомлення про помилку. Починаючи з PHP 7.4.0, це видає помилку рівня E_NOTICE; починаючи з PHP 8.0.0, це видає помилку рівня E_WARNING. Створення/змінення за допомогою синтаксису квадратних дужок Існуючий масив можна змінити, явно задавши в ньому значення. Це робиться шляхом присвоєння значень масиву (array) із зазначенням ключа в дужках. Ключ також можна опустити, що призведе до пустої пари дужок ([]). $arr[key] = value; $arr[] = value; // Ключ key може бути типом int або string // Значення value може бути будь-яким значенням будь-якого типу Якщо $arr ще не існує або має значення &null; або &false;, він буде створений, тому це також альтернативний спосіб створення масиву (array). Однак така практика не рекомендується, оскільки якщо $arr вже містить певне значення (наприклад, рядок (string) із змінної запиту), то це значення залишиться на місці, а [] може фактично означати оператор доступу до рядка. Завжди краще ініціалізувати змінну прямим присвоєнням. Починаючи з PHP 7.1.0, застосування оператора порожнього індексу до рядка викликає фатальну помилку. Раніше рядок автоматично перетворювався на масив. Починаючи з PHP 8.1.0, створення нового масиву приведенням до нього значення &false; застаріло. Створення нового масиву із &null; і невизначених значень все ще дозволено. Щоб змінити певне значення, призначте нове значення цьому елементу за допомогою його ключа. Щоб видалити пару ключ/значення, викликайте для неї функцію unset. 1, 12 => 2); $arr[] = 56; // Це те саме, що $arr[13] = 56; // на цьому етапі скрипта $arr["x"] = 42; // Це додає новий елемент // до масиву із ключем "x" unset($arr[5]); // Це видаляє елемент із масиву unset($arr); // Це видаляє весь масив ?> ]]> Як згадувалося вище, якщо ключ не вказано, береться максимальний з існуючих цілочисельних індексів int, і новим ключем буде це максимальне значення плюс 1 (але принаймні 0). Якщо цілочисельних індексів int ще не існує, ключ буде 0 (нуль). Зверніть увагу, що максимальний цілочисельний ключ, який використовується для цього, наразі не обов’язково існує в масиві.. Він повинен існувати в масиві лише деякий час з моменту останнього повторного індексування масиву. Наступний приклад ілюструє: $value) { unset($array[$i]); } print_r($array); // Додаємо елемент (зверніть увагу, що новий ключ має значення 5, а не 0). $array[] = 6; print_r($array); // Переіндексація: $array = array_values($array); $array[] = 7; print_r($array); ?> ]]> &example.outputs; 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 ) ]]> Деструктуризація масиву Масиви можна деструктурувати за допомогою мовних конструкцій [] (починаючи з PHP 7.1.0) або list. Ці конструкції можна використовувати для деструктурування масиву на окремі змінні. ]]> Деструктуризацію масиву можна використовувати у &foreach; для деструктуризації багатовимірного масиву під час ітерації по ньому. ]]> Елементи масиву ігноруватимуться, якщо змінна не вказана. Деструктуризація масиву завжди починається з індексу 0. ]]> Починаючи з PHP 7.1.0, асоціативні масиви також можна деструктурувати. Це також дозволяє легше вибирати потрібний елемент у масивах із числовими індексами, оскільки індекс можна вказати явно. 1, 'bar' => 2, 'baz' => 3]; // Призначаємо елемент з індексом 'baz' до змінної $three ['baz' => $three] = $source_array; echo $three; // виведе 3 $source_array = ['foo', 'bar', 'baz']; // Призначаємо елемент з індексом 2 до змінної $baz [2 => $baz] = $source_array; echo $baz; // виведе "baz" ?> ]]> Деструктуризація масиву може бути використана для легкої заміни двох змінних.. ]]> Оператор (...) не підтримується у призначеннях. Спроба отримати доступ до ключа масиву, який не було визначено, є такою самою, як доступ до будь-якої іншої невизначеної змінної: буде видано повідомлення про помилку рівня E_WARNING (рівень E_NOTICE до PHP 8.0.0), і результат буде &null;. Корисні функції Існує досить багато корисних функцій для роботи з масивами. Дивіться розділ "Функції для роботи з масивами". Функція unset дозволяє видаляти ключі з масиву. Майте на увазі, що масив НЕ буде повторно індексований. Якщо потрібна справжня поведінка «видалення та зміщення», масив можна переіндексувати за допомогою функції array_values. 'one', 2 => 'two', 3 => 'three'); unset($a[2]); /* створить масив, який був би визначений як: $a = array(1 => 'one', 3 => 'three'); a НЕ так: $a = array(1 => 'one', 2 => 'three'); */ $b = array_values($a); // Тепер $b це array(0 => 'one', 1 => 'three') ?> ]]> Керуюча структура &foreach; існує спеціально для масивів. Вона забезпечує простий спосіб обходу масиву. Array do's and don'ts Why is <literal>$foo[bar]</literal> wrong? Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts: ]]> This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that. The fallback to treat an undefined constant as bare string issues an error of level E_NOTICE. This has been deprecated as of PHP 7.2.0, and issues an error of level E_WARNING. As of PHP 8.0.0, it has been removed and throws an Error exception. This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them. ]]> &example.outputs; More examples to demonstrate this behaviour: 'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit']; // apple print $arr['veggie']; // carrot // Incorrect. This works but also throws a PHP error of level E_NOTICE because // of an undefined constant named fruit // // Notice: Use of undefined constant fruit - assumed 'fruit' in... print $arr[fruit]; // apple // This defines a constant to demonstrate what's going on. The value 'veggie' // is assigned to a constant named fruit. define('fruit', 'veggie'); // Notice the difference now print $arr['fruit']; // apple print $arr[fruit]; // carrot // The following is okay, as it's inside a string. Constants are not looked for // within strings, so no E_NOTICE occurs here print "Hello $arr[fruit]"; // Hello apple // With one exception: braces surrounding arrays within strings allows constants // to be interpreted print "Hello {$arr[fruit]}"; // Hello carrot print "Hello {$arr['fruit']}"; // Hello apple // This will not work, and will result in a parse error, such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using superglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> ]]> When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices. As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works: ]]> This is an example of using a function return value as the array index. PHP also knows about constants: ]]> Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing: ]]> because E_ERROR equals 1, etc. So why is it bad then? At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords. To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings. Converting to array For any of the types int, float, string, bool and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array) $scalarValue is exactly the same as array($scalarValue). If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have NUL bytes on either side. Uninitialized typed properties are silently discarded. {1} = null; } } var_export((array) new A()); ?> ]]> &example.outputs; NULL, '' . "\0" . '*' . "\0" . 'C' => NULL, 'D' => NULL, 1 => NULL, ) ]]> These NUL can result in some unexpected behaviour: ]]> &example.outputs; NULL ["AA"]=> NULL ["AA"]=> NULL } ]]> The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. Converting &null; to an array results in an empty array. Comparing It is possible to compare arrays with the array_diff function and with array operators. Array unpacking An array prefixed by ... will be expanded in place during array definition. Only arrays and objects which implement Traversable can be expanded. Array unpacking with ... is available as of PHP 7.4.0. It's possible to expand multiple times, and add normal elements before or after the ... operator: Simple array unpacking 'd']; //['a', 'b', 'c' => 'd'] ?> ]]> Unpacking an array with the ... operator follows the semantics of the array_merge function. That is, later string keys overwrite earlier ones and integer keys are renumbered: Array unpacking with duplicate key 1]; $arr2 = ["a" => 2]; $arr3 = ["a" => 0, ...$arr1, ...$arr2]; var_dump($arr3); // ["a" => 2] // integer key $arr4 = [1, 2, 3]; $arr5 = [4, 5, 6]; $arr6 = [...$arr4, ...$arr5]; var_dump($arr6); // [1, 2, 3, 4, 5, 6] // Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6] // where the original integer keys have not been retained. ?> ]]> Keys that are neither integers nor strings throw a TypeError. Such keys can only be generated by a Traversable object. Prior to PHP 8.1, unpacking an array which has a string key is not supported: 4]; $arr3 = [...$arr1, ...$arr2]; // Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5 $arr4 = [1, 2, 3]; $arr5 = [4, 5]; $arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5] ?> ]]> Examples The array type in PHP is very versatile. Here are some examples: 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); $b = array('a', 'b', 'c'); // . . .is completely equivalent with this: $a = array(); $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b = array(); $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // After the above code is executed, $a will be the array // array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', // 'name' => 'apple', 0 => 4), and $b will be the array // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c'). ?> ]]> Using array() 4, 'OS' => 'Linux', 'lang' => 'english', 'short_tags' => true ); // strictly numerical keys $array = array( 7, 8, 0, 156, -10 ); // this is the same as array(0 => 7, 1 => 8, ...) $switching = array( 10, // key = 0 5 => 6, 3 => 7, 'a' => 4, 11, // key = 6 (maximum of integer-indices was 5) '8' => 2, // key = 8 (integer!) '02' => 77, // key = '02' 0 => 12 // the value 10 will be overwritten by 12 ); // empty array $empty = array(); ?> ]]> Collection ]]> &example.outputs; Changing the values of the array directly is possible by passing them by reference. Changing element in the loop ]]> &example.outputs; RED [1] => BLUE [2] => GREEN [3] => YELLOW ) ]]> This example creates a one-based array. One-based index 'January', 'February', 'March'); print_r($firstquarter); ?> ]]> &example.outputs; 'January' [2] => 'February' [3] => 'March' ) ]]> Filling an array ]]> Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count function can be used to count the number of items in an array. Sorting an array ]]> Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays. Recursive and multi-dimensional arrays array ( "a" => "orange", "b" => "banana", "c" => "apple" ), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "first", 5 => "second", "third" ) ); // Some examples to address values in the array above echo $fruits["holes"][5]; // prints "second" echo $fruits["fruits"]["a"]; // prints "orange" unset($fruits["holes"][0]); // remove "first" // Create a new multi-dimensional array $juices["apple"]["green"] = "good"; ?> ]]> Array assignment always involves value copying. Use the reference operator to copy an array by reference. ]]>