1
0
mirror of https://github.com/php/doc-uk.git synced 2026-03-24 07:02:12 +01:00
Files
archived-doc-uk/language/types/array.xml
2024-10-10 18:51:09 +03:00

1451 lines
43 KiB
XML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?xml version="1.0" encoding="utf-8"?>
<!-- EN-Revision: 8859c8b96cd9e80652813f7bcf561432a5e9f934 Maintainer: neviksasha Status: wip -->
<sect1 xml:id="language.types.array">
<title>Масив (array)</title>
<para>
Масив в PHP - це упорядкована структура даних, яка зв'язує
<emphasis>значення</emphasis> і <emphasis>ключі</emphasis>. Цей тип
оптимізований для різних цілей, із ним можна працювати як із масивом, списком
(вектором), хеш-таблицею (реалізація карти), словником, колекцією, стеком,
чергою, і, мабуть, більше. Оскільки значення масиву можуть бути іншими масивами,
також можливі дерева та багатовимірні масиви.
</para>
<para>
Пояснення цих структур даних виходить за рамки цього посібника, але для кожної
з них надається принаймні один приклад. Щоб отримати додаткову інформацію,
перегляньте значну кількість літератури, яка існує на цю широку тему.
</para>
<sect2 xml:id="language.types.array.syntax">
<title>Синтаксис</title>
<sect3 xml:id="language.types.array.syntax.array-func">
<title>Зазначення використовуючи <function>array</function></title>
<para>
Масив (<type>array</type>) можна створити за допомогою мовної конструкції
<function>array</function>. Він приймає будь-яку кількість розділених комами
<literal><replaceable>ключ</replaceable> =&gt; <replaceable>значення</replaceable></literal>
пар як параметри.
</para>
<synopsis>
array(
<optional><replaceable>key</replaceable> =&gt; </optional><replaceable>value</replaceable>,
<optional><replaceable>key2</replaceable> =&gt; </optional><replaceable>value2</replaceable>,
<optional><replaceable>key3</replaceable> =&gt; </optional><replaceable>value3</replaceable>,
...
)</synopsis>
<!-- Do not fix the whitespace for the synopsis end element. A limitation of PhD prevents proper trimming -->
<para>
Кома після останнього елемента масиву необов’язкова, її можна опустити. Зазвичай це робиться
для однорядкових масивів, наприклад <literal>array(1, 2)</literal> вважається кращим, ніж
<literal>array(1, 2, )</literal>. З іншого боку, для багаторядкових масивів кінцева кома
зазвичай використовується, оскільки дозволяє легше додавати нові елементи в кінець.
</para>
<note>
<para>
Існує короткий синтаксис масиву, який замінює
<literal>array()</literal> на <literal>[]</literal>.
</para>
</note>
<example>
<title>Простий масив</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Використання короткого синтаксису масиву
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
]]>
</programlisting>
</example>
<para>
Ключ масиву (<replaceable>key</replaceable>) може бути заданий цілим числом
(<type>int</type>) або строкою (<type>string</type>). Значення масиву
(<replaceable>value</replaceable>) може бути будь-яким типом.
</para>
<para xml:id="language.types.array.key-casts">
Крім того, відбуватимуться наступні приведення ключів <replaceable>key</replaceable>:
<itemizedlist>
<listitem>
<simpara>
Рядки (<type>string</type>), що містять десяткові цілі числа (<type>int</type>)
(за винятком, коли перед числом не стоїть знак <literal>+</literal>), будуть приведені
до типу <type>int</type>. Наприклад ключ <literal>"8"</literal> фактично зберігатиметься
під <literal>8</literal>. З іншого боку, <literal>"08"</literal> не буде приведено,
оскільки це недійсне десяткове ціле число.
</simpara>
</listitem>
<listitem>
<simpara>
Десяткові дроби (<type>float</type>) також перетворюються на цілі числа (<type>int</type>),
що означає, що дробова частина буде скорочена. Наприклад ключ <literal>8.7</literal> фактично
зберігатиметься під <literal>8</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Логічний тип (<type>bool</type>) також перетворюється на ціле число (<type>int</type>), тобто ключ
&true; фактично зберігатиметься під <literal>1</literal>, а ключ &false; під <literal>0</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Тип <type>null</type> буде приведено до порожнього рядка, тобто ключ
<literal>null</literal> фактично зберігатиметься під <literal>""</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Масиви (<type>array</type>) та обʼєкти (<type>object</type>) <emphasis>не можуть</emphasis>
бути використані як ключі.
Це призведе до попередження: <literal>Illegal offset type</literal>.
</simpara>
</listitem>
</itemizedlist>
</para>
<para>
Якщо кілька елементів в оголошенні масиву використовують той самий ключ, буде використано
лише останній, оскільки всі інші буде перезаписано.
</para>
<example>
<title>Приклад переведення типів і перезапису</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(1) {
[1]=>
string(1) "d"
}
]]>
</screen>
<para>
Оскільки всі ключі у наведеному вище прикладі приведено до <literal>1</literal>,
значення буде перезаписано на кожному новому елементі, та залишиться тільки
останнє присвоєне значення <literal>"d"</literal>.
</para>
</example>
<para>
Масиви PHP можуть містити цілочисленні (<type>int</type>) і строкові (<type>string</type>)
ключі одночасно, оскільки PHP не розрізняє індексовані та асоціативні масиви.
</para>
<example>
<title>Змішані цілочисленні (<type>int</type>) і строкові (<type>string</type>) ключі</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(4) {
["foo"]=>
string(3) "bar"
["bar"]=>
string(3) "foo"
[100]=>
int(-100)
[-100]=>
int(100)
}
]]>
</screen>
</example>
<para>
Ключ (<replaceable>key</replaceable>) необов'язковий. Якщо його не вказано, PHP
використовуватиме приріст найбільшого раніше використаного цілого (<type>int</type>) ключа.
</para>
<example>
<title>Індексовані масиви без ключа</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(5) "hello"
[3]=>
string(5) "world"
}
]]>
</screen>
</example>
<para>
Можна вказати ключ для одних елементів і не вказати для інших:
</para>
<example>
<title>Ключі не на всіх елементах</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[6]=>
string(1) "c"
[7]=>
string(1) "d"
}
]]>
</screen>
<para>
Як ви бачите, останньому значенню <literal>"d"</literal> було присвоєно
ключ <literal>7</literal>. Це тому, що найбільший цілий ключ до цього
був <literal>6</literal>.
</para>
</example>
<example>
<title>Приклад складного приведення типу та перезапису</title>
<para>
Цей приклад включає всі варіанти приведення типів ключів і перезапису
елементів.
</para>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
1 => '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);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(7) {
[1]=>
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"
}
]]>
</screen>
</example>
</sect3>
<sect3 xml:id="language.types.array.syntax.accessing">
<title>Доступ до елементів масиву за допомогою синтаксису квадратних дужок</title>
<para>
Доступ до елементів масиву можна отримати за допомогою синтаксису <literal>array[key]</literal>.
</para>
<example>
<title>Доступ до елементів масиву</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
string(3) "bar"
int(24)
string(3) "foo"
]]>
</screen>
</example>
<note>
<para>
До PHP 8.0.0 квадратні та фігурні дужки могли використовуватися як взаємозамінні
для доступу до елементів масиву (наприклад, <literal>$array[42]</literal> і <literal>$array{42}</literal>
робили б те саме у прикладі вище).
Синтаксис фігурних дужок застарів із PHP 7.4.0 і більше не підтримується з PHP 8.0.0.
</para>
</note>
<example>
<title>Розіменування масиву</title>
<programlisting role="php">
<![CDATA[
<?php
function getArray() {
return array(1, 2, 3);
}
$secondElement = getArray()[1];
?>
]]>
</programlisting>
</example>
<note>
<para>
Спроба отримати доступ до ключа масиву, який не було визначено,
це теж саме, як доступ до будь-якої іншої невизначеної змінної:
буде видано помилку рівня <constant>E_WARNING</constant>
(рівень <constant>E_NOTICE</constant> до PHP 8.0.0), і результат буде &null;.
</para>
</note>
<note>
<para>
Розіменування масиву скалярного значення, яке не є рядком (<type>string</type>),
дає &null;. До PHP 7.4.0 це не видавало повідомлення про помилку.
Починаючи з PHP 7.4.0, це видає помилку рівня <constant>E_NOTICE</constant>;
починаючи з PHP 8.0.0, це видає помилку рівня <constant>E_WARNING</constant>.
</para>
</note>
</sect3>
<sect3 xml:id="language.types.array.syntax.modifying">
<title>Створення/змінення за допомогою синтаксису квадратних дужок</title>
<para>
Існуючий масив можна змінити, явно задавши в ньому значення.
</para>
<para>
Це робиться шляхом присвоєння значень масиву (<type>array</type>) із зазначенням
ключа в дужках. Ключ також можна опустити, що призведе до пустої пари дужок (<literal>[]</literal>).
</para>
<synopsis>
$arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>;
$arr[] = <replaceable>value</replaceable>;
// Ключ <replaceable>key</replaceable> може бути типом <type>int</type> або <type>string</type>
// Значення <replaceable>value</replaceable> може бути будь-яким значенням будь-якого типу</synopsis>
<para>
Якщо <varname>$arr</varname> ще не існує або має значення &null; або &false;, він буде створений,
тому це також альтернативний спосіб створення масиву (<type>array</type>). Однак така практика
не рекомендується, оскільки якщо <varname>$arr</varname> вже містить певне значення (наприклад,
рядок (<type>string</type>) із змінної запиту), то це значення залишиться на місці, а <literal>[]</literal>
може фактично означати <link linkend="language.types.string.substr">оператор доступу до рядка</link>.
Завжди краще ініціалізувати змінну прямим присвоєнням.
</para>
<note>
<simpara>
Починаючи з PHP 7.1.0, застосування оператора порожнього індексу до рядка
викликає фатальну помилку. Раніше рядок автоматично перетворювався на масив.
</simpara>
</note>
<note>
<simpara>
Починаючи з PHP 8.1.0, створення нового масиву приведенням до нього значення &false; застаріло.
Створення нового масиву із &null; і невизначених значень все ще дозволено.
</simpara>
</note>
<para>
Щоб змінити певне значення, призначте нове значення цьому елементу за допомогою його ключа.
Щоб видалити пару ключ/значення, викликайте для неї функцію <function>unset</function>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // Це те саме, що $arr[13] = 56;
// на цьому етапі скрипта
$arr["x"] = 42; // Це додає новий елемент
// до масиву із ключем "x"
unset($arr[5]); // Це видаляє елемент із масиву
unset($arr); // Це видаляє весь масив
?>
]]>
</programlisting>
</informalexample>
<note>
<para>
Як згадувалося вище, якщо ключ не вказано, береться максимальний з існуючих
цілочисельних індексів <type>int</type>, і новим ключем буде це максимальне значення плюс 1
(але принаймні 0). Якщо цілочисельних індексів <type>int</type> ще не існує, ключ буде
<literal>0</literal> (нуль).
</para>
<para>
Зверніть увагу, що максимальний цілочисельний ключ, який використовується для цього,
<emphasis>наразі не обов’язково існує в масиві.</emphasis>. Він повинен існувати в масиві
лише деякий час з моменту останнього повторного індексування масиву. Наступний приклад ілюструє:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Створюємо простий масив.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Тепер видалимо усі елементи, але залишимо сам масив без змін:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Додаємо елемент (зверніть увагу, що новий ключ має значення 5, а не 0).
$array[] = 6;
print_r($array);
// Переіндексація:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
)
Array
(
[5] => 6
)
Array
(
[0] => 6
[1] => 7
)
]]>
</screen>
</informalexample>
</note>
</sect3>
<sect3 xml:id="language.types.array.syntax.destructuring">
<title>Деструктуризація масиву</title>
<para>
Масиви можна деструктурувати за допомогою мовних конструкцій <literal>[]</literal>
(починаючи з PHP 7.1.0) або <function>list</function>. Ці конструкції можна
використовувати для деструктурування масиву на окремі змінні.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo', 'bar', 'baz'];
[$foo, $bar, $baz] = $source_array;
echo $foo; // виведе "foo"
echo $bar; // виведе "bar"
echo $baz; // виведе "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
Деструктуризацію масиву можна використовувати у &foreach; для
деструктуризації багатовимірного масиву під час ітерації по ньому.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = [
[1, 'John'],
[2, 'Jane'],
];
foreach ($source_array as [$id, $name]) {
// логіка роботи із $id і $name
}
?>
]]>
</programlisting>
</informalexample>
<para>
Елементи масиву ігноруватимуться, якщо змінна не вказана.
Деструктуризація масиву завжди починається з індексу <literal>0</literal>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo', 'bar', 'baz'];
// Признаємо елемент з індексом 2 до змінної $baz
[, , $baz] = $source_array;
echo $baz; // виведе "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
Починаючи з PHP 7.1.0, асоціативні масиви також можна деструктурувати.
Це також дозволяє легше вибирати потрібний елемент у масивах із
числовими індексами, оскільки індекс можна вказати явно.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo' => 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"
?>
]]>
</programlisting>
</informalexample>
<para>
Деструктуризація масиву може бути використана для легкої заміни двох змінних..
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 1;
$b = 2;
[$b, $a] = [$a, $b];
echo $a; // виведе 2
echo $b; // виведе 1
?>
]]>
</programlisting>
</informalexample>
<note>
<para>
Оператор (<literal>...</literal>) не підтримується у призначеннях.
</para>
</note>
<note>
<para>
Спроба отримати доступ до ключа масиву, який не було визначено,
є такою самою, як доступ до будь-якої іншої невизначеної змінної:
буде видано повідомлення про помилку рівня <constant>E_WARNING</constant>
(рівень <constant>E_NOTICE</constant> до PHP 8.0.0), і результат буде &null;.
</para>
</note>
</sect3>
</sect2><!-- end syntax -->
<sect2 xml:id="language.types.array.useful-funcs">
<title>Корисні функції</title>
<para>
Існує досить багато корисних функцій для роботи з масивами.
Дивіться розділ "<link linkend="ref.array">Функції для роботи з масивами</link>".
</para>
<note>
<para>
Функція <function>unset</function> дозволяє видаляти ключі з масиву. Майте на увазі,
що масив <emphasis>НЕ</emphasis> буде повторно індексований. Якщо потрібна справжня
поведінка «видалення та зміщення», масив можна переіндексувати за допомогою
функції <function>array_values</function>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = array(1 => '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')
?>
]]>
</programlisting>
</informalexample>
</note>
<para>
Керуюча структура &foreach; існує спеціально для масивів.
Вона забезпечує простий спосіб обходу масиву.
</para>
</sect2>
<sect2 xml:id="language.types.array.donts">
<title>Array do's and don'ts</title>
<sect3 xml:id="language.types.array.foo-bar">
<title>Why is <literal>$foo[bar]</literal> wrong?</title>
<para>
Always use quotes around a string literal array index. For example,
<literal>$foo['bar']</literal> is correct, while
<literal>$foo[bar]</literal> is not. But why? It is common to encounter this
kind of syntax in old scripts:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
?>
]]>
</programlisting>
</informalexample>
<para>
This is wrong, but it works. The reason is that this code has an undefined
constant (<literal>bar</literal>) rather than a <type>string</type> (<literal>'bar'</literal> - notice the
quotes). It works because PHP automatically converts a
<emphasis>bare string</emphasis> (an unquoted <type>string</type> which does
not correspond to any known symbol) into a <type>string</type> which
contains the bare <type>string</type>. For instance, if there is no defined
constant named <constant>bar</constant>, then PHP will substitute in the
<type>string</type> <literal>'bar'</literal> and use that.
</para>
<warning>
<simpara>
The fallback to treat an undefined constant as bare string issues an error
of level <constant>E_NOTICE</constant>.
This has been deprecated as of PHP 7.2.0, and issues an error
of level <constant>E_WARNING</constant>.
As of PHP 8.0.0, it has been removed and throws an
<classname>Error</classname> exception.
</simpara>
</warning>
<note>
<simpara>
This does not mean to <emphasis>always</emphasis> quote the key. Do not
quote keys which are <link linkend="language.constants">constants</link> or
<link linkend="language.variables">variables</link>, as this will prevent
PHP from interpreting them.
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\nChecking $i: \n";
echo "Bad: " . $array['$i'] . "\n";
echo "Good: " . $array[$i] . "\n";
echo "Bad: {$array['$i']}\n";
echo "Good: {$array[$i]}\n";
}
?>
]]>
</programlisting>
</informalexample>
&example.outputs;
<screen>
<![CDATA[
Checking 0:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 1
Checking 1:
Notice: Undefined index: $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index: $i in /path/to/script.html on line 11
Bad:
Good: 2
]]>
</screen>
</note>
<para>
More examples to demonstrate this behaviour:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// Show all errors
error_reporting(E_ALL);
$arr = array('fruit' => '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
?>
]]>
</programlisting>
</informalexample>
<para>
When <link linkend="ini.error-reporting">error_reporting</link> is set to
show <constant>E_NOTICE</constant> level errors (by setting it to
<constant>E_ALL</constant>, for example), such uses will become immediately
visible. By default,
<link linkend="ini.error-reporting">error_reporting</link> is set not to
show notices.
</para>
<para>
As stated in the <link linkend="language.types.array.syntax">syntax</link>
section, what's inside the square brackets ('<literal>[</literal>' and
'<literal>]</literal>') must be an expression. This means that code like
this works:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
echo $arr[somefunc($bar)];
?>
]]>
</programlisting>
</informalexample>
<para>
This is an example of using a function return value as the array index. PHP
also knows about constants:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$error_descriptions[E_ERROR] = "A fatal error has occurred";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
?>
]]>
</programlisting>
</informalexample>
<para>
Note that <constant>E_ERROR</constant> is also a valid identifier, just like
<literal>bar</literal> in the first example. But the last example is in fact
the same as writing:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$error_descriptions[1] = "A fatal error has occurred";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>
]]>
</programlisting>
</informalexample>
<para>
because <constant>E_ERROR</constant> equals <literal>1</literal>, etc.
</para>
<sect4 xml:id="language.types.array.foo-bar.why">
<title>So why is it bad then?</title>
<para>
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 <literal>empty</literal> and
<literal>default</literal> this way, since they are
<link linkend="reserved">reserved keywords</link>.
</para>
<note>
<simpara>
To reiterate, inside a double-quoted <type>string</type>, it's valid to
not surround array indexes with quotes so <literal>"$foo[bar]"</literal>
is valid. See the above examples for details on why as well as the section
on <link linkend="language.types.string.parsing">variable parsing in
strings</link>.
</simpara>
</note>
</sect4>
</sect3>
</sect2>
<sect2 xml:id="language.types.array.casting">
<title>Converting to array</title>
<para>
For any of the types <type>int</type>, <type>float</type>,
<type>string</type>, <type>bool</type> and <type>resource</type>,
converting a value to an <type>array</type> results in an array with a single
element with index zero and the value of the scalar which was converted. In
other words, <code>(array) $scalarValue</code> is exactly the same as
<literal>array($scalarValue)</literal>.
</para>
<para>
If an <type>object</type> is converted to an <type>array</type>, the result
is an <type>array</type> whose elements are the <type>object</type>'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 <literal>NUL</literal> bytes on either side.
Uninitialized <link linkend="language.oop5.properties.typed-properties">typed properties</link>
are silently discarded.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A {
private $B;
protected $C;
public $D;
function __construct()
{
$this->{1} = null;
}
}
var_export((array) new A());
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array (
'' . "\0" . 'A' . "\0" . 'B' => NULL,
'' . "\0" . '*' . "\0" . 'C' => NULL,
'D' => NULL,
1 => NULL,
)
]]>
</screen>
</informalexample>
<para>
These <literal>NUL</literal> can result in some unexpected behaviour:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A {
private $A; // This will become '\0A\0A'
}
class B extends A {
private $A; // This will become '\0B\0A'
public $AA; // This will become 'AA'
}
var_dump((array) new B());
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(3) {
["BA"]=>
NULL
["AA"]=>
NULL
["AA"]=>
NULL
}
]]>
</screen>
</informalexample>
<para>
The above will appear to have two keys named 'AA', although one of them is
actually named '\0A\0A'.
</para>
<para>
Converting &null; to an <type>array</type> results in an empty
<type>array</type>.
</para>
</sect2>
<sect2 xml:id="language.types.array.comparing">
<title>Comparing</title>
<para>
It is possible to compare arrays with the <function>array_diff</function>
function and with
<link linkend="language.operators.array">array operators</link>.
</para>
</sect2>
<sect2 xml:id="language.types.array.unpacking">
<title>Array unpacking</title>
<para>
An array prefixed by <code>...</code> will be expanded in place during array definition.
Only arrays and objects which implement <interfacename>Traversable</interfacename> can be expanded.
Array unpacking with <code>...</code> is available as of PHP 7.4.0.
</para>
<para>
It's possible to expand multiple times, and add normal elements before or after the <code>...</code> operator:
<example>
<title>Simple array unpacking</title>
<programlisting role="php">
<![CDATA[
<?php
// Using short array syntax.
// Also, works with array() syntax.
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = [...$arr1, ...$arr2, 111]; //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c' => 'd']; //['a', 'b', 'c' => 'd']
?>
]]>
</programlisting>
</example>
</para>
<para>
Unpacking an array with the <code>...</code> operator follows the semantics of the <function>array_merge</function> function.
That is, later string keys overwrite earlier ones and integer keys are renumbered:
<example>
<title>Array unpacking with duplicate key</title>
<programlisting role="php">
<![CDATA[
<?php
// string key
$arr1 = ["a" => 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.
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Keys that are neither integers nor strings throw a <classname>TypeError</classname>.
Such keys can only be generated by a <interfacename>Traversable</interfacename> object.
</para>
</note>
<note>
<para>
Prior to PHP 8.1, unpacking an array which has a string key is not supported:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr1 = [1, 2, 3];
$arr2 = ['a' => 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]
?>
]]>
</programlisting>
</informalexample>
</note>
</sect2>
<sect2 xml:id="language.types.array.examples">
<title>Examples</title>
<para>
The array type in PHP is very versatile. Here are some examples:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// This:
$a = array( 'color' => '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').
?>
]]>
</programlisting>
</informalexample>
<example>
<title>Using array()</title>
<programlisting role="php">
<![CDATA[
<?php
// Array as (property-)map
$map = array( 'version' => 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();
?>
]]>
<!-- TODO example of
- overwriting keys
- using vars/functions as key/values
- warning about references
-->
</programlisting>
</example>
<example xml:id="language.types.array.examples.loop">
<title>Collection</title>
<programlisting role="php">
<![CDATA[
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
]]>
</screen>
</example>
<para>
Changing the values of the <type>array</type> directly is possible
by passing them by reference.
</para>
<example xml:id="language.types.array.examples.changeloop">
<title>Changing element in the loop</title>
<programlisting role="php">
<![CDATA[
<?php
foreach ($colors as &$color) {
$color = mb_strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
print_r($colors);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
]]>
</screen>
</example>
<para>
This example creates a one-based array.
</para>
<example>
<title>One-based index</title>
<programlisting role="php">
<![CDATA[
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
]]>
</screen>
</example>
<example>
<title>Filling an array</title>
<programlisting role="php">
<![CDATA[
<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>
]]>
</programlisting>
</example>
<para>
<type>Array</type>s are ordered. The order can be changed using various
sorting functions. See the <link linkend="ref.array">array functions</link>
section for more information. The <function>count</function> function can be
used to count the number of items in an <type>array</type>.
</para>
<example>
<title>Sorting an array</title>
<programlisting role="php">
<![CDATA[
<?php
sort($files);
print_r($files);
?>
]]>
</programlisting>
</example>
<para>
Because the value of an <type>array</type> can be anything, it can also be
another <type>array</type>. This enables the creation of recursive and
multi-dimensional <type>array</type>s.
</para>
<example>
<title>Recursive and multi-dimensional arrays</title>
<programlisting role="php">
<![CDATA[
<?php
$fruits = array ( "fruits" => 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";
?>
]]>
</programlisting>
</example>
<para>
<type>Array</type> assignment always involves value copying. Use the
<link linkend="language.operators">reference operator</link> to copy an
<type>array</type> by reference.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
]]>
</programlisting>
</informalexample>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->