Масив (array)

Масив Π² PHP - Ρ†Π΅ упорядкована структура Π΄Π°Π½ΠΈΡ…, яка Π·Π²'язує значСння Ρ– ΠΊΠ»ΡŽΡ‡Ρ–. Π¦Π΅ΠΉ Ρ‚ΠΈΠΏ ΠΎΠΏΡ‚ΠΈΠΌΡ–Π·ΠΎΠ²Π°Π½ΠΈΠΉ для Ρ€Ρ–Π·Π½ΠΈΡ… Ρ†Ρ–Π»Π΅ΠΉ, Ρ–Π· Π½ΠΈΠΌ ΠΌΠΎΠΆΠ½Π° ΠΏΡ€Π°Ρ†ΡŽΠ²Π°Ρ‚ΠΈ як Ρ–Π· масивом, списком (Π²Π΅ΠΊΡ‚ΠΎΡ€ΠΎΠΌ), Ρ…Π΅Ρˆ-Ρ‚Π°Π±Π»ΠΈΡ†Π΅ΡŽ (рСалізація ΠΊΠ°Ρ€Ρ‚ΠΈ), словником, ΠΊΠΎΠ»Π΅ΠΊΡ†Ρ–Ρ”ΡŽ, стСком, Ρ‡Π΅Ρ€Π³ΠΎΡŽ, Ρ–, ΠΌΠ°Π±ΡƒΡ‚ΡŒ, Π±Ρ–Π»ΡŒΡˆΠ΅. ΠžΡΠΊΡ–Π»ΡŒΠΊΠΈ значСння масиву ΠΌΠΎΠΆΡƒΡ‚ΡŒ Π±ΡƒΡ‚ΠΈ Ρ–Π½ΡˆΠΈΠΌΠΈ масивами, Ρ‚Π°ΠΊΠΎΠΆ ΠΌΠΎΠΆΠ»ΠΈΠ²Ρ– Π΄Π΅Ρ€Π΅Π²Π° Ρ‚Π° Π±Π°Π³Π°Ρ‚ΠΎΠ²ΠΈΠΌΡ–Ρ€Π½Ρ– масиви.

ПояснСння Ρ†ΠΈΡ… структур Π΄Π°Π½ΠΈΡ… Π²ΠΈΡ…ΠΎΠ΄ΠΈΡ‚ΡŒ Π·Π° Ρ€Π°ΠΌΠΊΠΈ Ρ†ΡŒΠΎΠ³ΠΎ посібника, Π°Π»Π΅ для ΠΊΠΎΠΆΠ½ΠΎΡ— Π· Π½ΠΈΡ… Π½Π°Π΄Π°Ρ”Ρ‚ΡŒΡΡ ΠΏΡ€ΠΈΠ½Π°ΠΉΠΌΠ½Ρ– ΠΎΠ΄ΠΈΠ½ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄. Π©ΠΎΠ± ΠΎΡ‚Ρ€ΠΈΠΌΠ°Ρ‚ΠΈ Π΄ΠΎΠ΄Π°Ρ‚ΠΊΠΎΠ²Ρƒ Ρ–Π½Ρ„ΠΎΡ€ΠΌΠ°Ρ†Ρ–ΡŽ, ΠΏΠ΅Ρ€Π΅Π³Π»ΡΠ½ΡŒΡ‚Π΅ Π·Π½Π°Ρ‡Π½Ρƒ ΠΊΡ–Π»ΡŒΠΊΡ–ΡΡ‚ΡŒ Π»Ρ–Ρ‚Π΅Ρ€Π°Ρ‚ΡƒΡ€ΠΈ, яка існує Π½Π° Ρ†ΡŽ ΡˆΠΈΡ€ΠΎΠΊΡƒ Ρ‚Π΅ΠΌΡƒ.

Бинтаксис

ЗазначСння Π²ΠΈΠΊΠΎΡ€ΠΈΡΡ‚ΠΎΠ²ΡƒΡŽΡ‡ΠΈ array()

Масив (array) ΠΌΠΎΠΆΠ½Π° створити Π·Π° допомогою ΠΌΠΎΠ²Π½ΠΎΡ— конструкції array(). Π’Ρ–Π½ ΠΏΡ€ΠΈΠΉΠΌΠ°Ρ” Π±ΡƒΠ΄ΡŒ-яку ΠΊΡ–Π»ΡŒΠΊΡ–ΡΡ‚ΡŒ Ρ€ΠΎΠ·Π΄Ρ–Π»Π΅Π½ΠΈΡ… ΠΊΠΎΠΌΠ°ΠΌΠΈ ΠΊΠ»ΡŽΡ‡ => значСння ΠΏΠ°Ρ€ як ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΈ.

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

Кома після ΠΎΡΡ‚Π°Π½Π½ΡŒΠΎΠ³ΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Π° масиву нСобов’язкова, Ρ—Ρ— ΠΌΠΎΠΆΠ½Π° опустити. Π—Π°Π·Π²ΠΈΡ‡Π°ΠΉ Ρ†Π΅ Ρ€ΠΎΠ±ΠΈΡ‚ΡŒΡΡ для однорядкових масивів, Π½Π°ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ array(1, 2) Π²Π²Π°ΠΆΠ°Ρ”Ρ‚ΡŒΡΡ ΠΊΡ€Π°Ρ‰ΠΈΠΌ, Π½Ρ–ΠΆ array(1, 2, ). Π— Ρ–Π½ΡˆΠΎΠ³ΠΎ Π±ΠΎΠΊΡƒ, для багаторядкових масивів ΠΊΡ–Π½Ρ†Π΅Π²Π° ΠΊΠΎΠΌΠ° Π·Π°Π·Π²ΠΈΡ‡Π°ΠΉ Π²ΠΈΠΊΠΎΡ€ΠΈΡΡ‚ΠΎΠ²ΡƒΡ”Ρ‚ΡŒΡΡ, ΠΎΡΠΊΡ–Π»ΡŒΠΊΠΈ дозволяє лСгшС Π΄ΠΎΠ΄Π°Π²Π°Ρ‚ΠΈ Π½ΠΎΠ²Ρ– Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚ΠΈ Π² ΠΊΡ–Π½Π΅Ρ†ΡŒ.

ЗауваТСння:

Існує ΠΊΠΎΡ€ΠΎΡ‚ΠΊΠΈΠΉ синтаксис масиву, який Π·Π°ΠΌΡ–Π½ΡŽΡ” array() Π½Π° [].

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #1 ΠŸΡ€ΠΎΡΡ‚ΠΈΠΉ масив

<?php
$array
= array(
"foo" => "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.

Π―ΠΊΡ‰ΠΎ ΠΊΡ–Π»ΡŒΠΊΠ° Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π² Π² ΠΎΠ³ΠΎΠ»ΠΎΡˆΠ΅Π½Π½Ρ– масиву Π²ΠΈΠΊΠΎΡ€ΠΈΡΡ‚ΠΎΠ²ΡƒΡŽΡ‚ΡŒ Ρ‚ΠΎΠΉ самий ΠΊΠ»ΡŽΡ‡, Π±ΡƒΠ΄Π΅ використано лишС останній, ΠΎΡΠΊΡ–Π»ΡŒΠΊΠΈ всі Ρ–Π½ΡˆΡ– Π±ΡƒΠ΄Π΅ пСрСзаписано.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #2 ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ пСрСвСдСння Ρ‚ΠΈΠΏΡ–Π² Ρ– пСрСзапису

<?php
$array
= array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

array(1) {
  [1]=>
  string(1) "d"
}

ΠžΡΠΊΡ–Π»ΡŒΠΊΠΈ всі ΠΊΠ»ΡŽΡ‡Ρ– Ρƒ Π½Π°Π²Π΅Π΄Π΅Π½ΠΎΠΌΡƒ Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄Ρ– ΠΏΡ€ΠΈΠ²Π΅Π΄Π΅Π½ΠΎ Π΄ΠΎ 1, значСння Π±ΡƒΠ΄Π΅ пСрСзаписано Π½Π° ΠΊΠΎΠΆΠ½ΠΎΠΌΡƒ Π½ΠΎΠ²ΠΎΠΌΡƒ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–, Ρ‚Π° Π·Π°Π»ΠΈΡˆΠΈΡ‚ΡŒΡΡ Ρ‚Ρ–Π»ΡŒΠΊΠΈ останнє присвоєнС значСння "d".

Масиви PHP ΠΌΠΎΠΆΡƒΡ‚ΡŒ містити цілочислСнні (int) Ρ– строкові (string) ΠΊΠ»ΡŽΡ‡Ρ– одночасно, ΠΎΡΠΊΡ–Π»ΡŒΠΊΠΈ PHP Π½Π΅ розрізняє індСксовані Ρ‚Π° асоціативні масиви.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #3 Π—ΠΌΡ–ΡˆΠ°Π½Ρ– цілочислСнні (int) Ρ– строкові (string) ΠΊΠ»ΡŽΡ‡Ρ–

<?php
$array
= array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-
100 => 100,
);
var_dump($array);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

ΠšΠ»ΡŽΡ‡ (key) Π½Π΅ΠΎΠ±ΠΎΠ²'язковий. Π―ΠΊΡ‰ΠΎ ΠΉΠΎΠ³ΠΎ Π½Π΅ Π²ΠΊΠ°Π·Π°Π½ΠΎ, PHP використовуватимС приріст Π½Π°ΠΉΠ±Ρ–Π»ΡŒΡˆΠΎΠ³ΠΎ Ρ€Π°Π½Ρ–ΡˆΠ΅ використаного Ρ†Ρ–Π»ΠΎΠ³ΠΎ (int) ΠΊΠ»ΡŽΡ‡Π°.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #4 ІндСксовані масиви Π±Π΅Π· ΠΊΠ»ΡŽΡ‡Π°

<?php
$array
= array("foo", "bar", "hello", "world");
var_dump($array);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

МоТна Π²ΠΊΠ°Π·Π°Ρ‚ΠΈ ΠΊΠ»ΡŽΡ‡ для ΠΎΠ΄Π½ΠΈΡ… Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π² Ρ– Π½Π΅ Π²ΠΊΠ°Π·Π°Ρ‚ΠΈ для Ρ–Π½ΡˆΠΈΡ…:

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #5 ΠšΠ»ΡŽΡ‡Ρ– Π½Π΅ Π½Π° всіх Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Π°Ρ…

<?php
$array
= array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

Π―ΠΊ Π²ΠΈ Π±Π°Ρ‡ΠΈΡ‚Π΅, ΠΎΡΡ‚Π°Π½Π½ΡŒΠΎΠΌΡƒ Π·Π½Π°Ρ‡Π΅Π½Π½ΡŽ "d" Π±ΡƒΠ»ΠΎ присвоєно ΠΊΠ»ΡŽΡ‡ 7. Π¦Π΅ Ρ‚ΠΎΠΌΡƒ, Ρ‰ΠΎ Π½Π°ΠΉΠ±Ρ–Π»ΡŒΡˆΠΈΠΉ Ρ†Ρ–Π»ΠΈΠΉ ΠΊΠ»ΡŽΡ‡ Π΄ΠΎ Ρ†ΡŒΠΎΠ³ΠΎ Π±ΡƒΠ² 6.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #6 ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ складного привСдСння Ρ‚ΠΈΠΏΡƒ Ρ‚Π° пСрСзапису

Π¦Π΅ΠΉ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΊΠ»ΡŽΡ‡Π°Ρ” всі Π²Π°Ρ€Ρ–Π°Π½Ρ‚ΠΈ привСдСння Ρ‚ΠΈΠΏΡ–Π² ΠΊΠ»ΡŽΡ‡Ρ–Π² Ρ– пСрСзапису Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π².

<?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);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

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"
}

Доступ Π΄ΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π² масиву Π·Π° допомогою синтаксису ΠΊΠ²Π°Π΄Ρ€Π°Ρ‚Π½ΠΈΡ… Π΄ΡƒΠΆΠΎΠΊ

Доступ Π΄ΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π² масиву ΠΌΠΎΠΆΠ½Π° ΠΎΡ‚Ρ€ΠΈΠΌΠ°Ρ‚ΠΈ Π·Π° допомогою синтаксису array[key].

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #7 Доступ Π΄ΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π² масиву

<?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"]);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

string(3) "bar"
int(24)
string(3) "foo"

ЗауваТСння:

Π”ΠΎ PHP 8.0.0 ΠΊΠ²Π°Π΄Ρ€Π°Ρ‚Π½Ρ– Ρ‚Π° Ρ„Ρ–Π³ΡƒΡ€Π½Ρ– Π΄ΡƒΠΆΠΊΠΈ ΠΌΠΎΠ³Π»ΠΈ використовуватися як Π²Π·Π°Ρ”ΠΌΠΎΠ·Π°ΠΌΡ–Π½Π½Ρ– для доступу Π΄ΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚Ρ–Π² масиву (Π½Π°ΠΏΡ€ΠΈΠΊΠ»Π°Π΄, $array[42] Ρ– $array{42} Ρ€ΠΎΠ±ΠΈΠ»ΠΈ Π± Ρ‚Π΅ самС Ρƒ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄Ρ– Π²ΠΈΡ‰Π΅). Бинтаксис Ρ„Ρ–Π³ΡƒΡ€Π½ΠΈΡ… Π΄ΡƒΠΆΠΎΠΊ застарів Ρ–Π· PHP 7.4.0 Ρ– Π±Ρ–Π»ΡŒΡˆΠ΅ Π½Π΅ ΠΏΡ–Π΄Ρ‚Ρ€ΠΈΠΌΡƒΡ”Ρ‚ΡŒΡΡ Π· PHP 8.0.0.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #8 РозімСнування масиву

<?php
function getArray() {
return array(
1, 2, 3);
}

$secondElement = getArray()[1];
?>

ЗауваТСння:

Π‘ΠΏΡ€ΠΎΠ±Π° ΠΎΡ‚Ρ€ΠΈΠΌΠ°Ρ‚ΠΈ доступ Π΄ΠΎ ΠΊΠ»ΡŽΡ‡Π° масиву, який Π½Π΅ Π±ΡƒΠ»ΠΎ Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½ΠΎ, Ρ†Π΅ Ρ‚Π΅ΠΆ самС, як доступ Π΄ΠΎ Π±ΡƒΠ΄ΡŒ-якої Ρ–Π½ΡˆΠΎΡ— Π½Π΅Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½ΠΎΡ— Π·ΠΌΡ–Π½Π½ΠΎΡ—: Π±ΡƒΠ΄Π΅ Π²ΠΈΠ΄Π°Π½ΠΎ ΠΏΠΎΠΌΠΈΠ»ΠΊΡƒ рівня 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().

<?php
$arr
= array(5 => 1, 12 => 2);

$arr[] = 56; // Π¦Π΅ Ρ‚Π΅ самС, Ρ‰ΠΎ $arr[13] = 56;
// Π½Π° Ρ†ΡŒΠΎΠΌΡƒ Π΅Ρ‚Π°ΠΏΡ– скрипта

$arr["x"] = 42; // Π¦Π΅ Π΄ΠΎΠ΄Π°Ρ” Π½ΠΎΠ²ΠΈΠΉ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚
// Π΄ΠΎ масиву Ρ–Π· ΠΊΠ»ΡŽΡ‡Π΅ΠΌ "x"

unset($arr[5]); // Π¦Π΅ видаляє Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚ Ρ–Π· масиву

unset($arr); // Π¦Π΅ видаляє вСсь масив
?>

ЗауваТСння:

Π―ΠΊ згадувалося Π²ΠΈΡ‰Π΅, якщо ΠΊΠ»ΡŽΡ‡ Π½Π΅ Π²ΠΊΠ°Π·Π°Π½ΠΎ, Π±Π΅Ρ€Π΅Ρ‚ΡŒΡΡ максимальний Π· Ρ–ΡΠ½ΡƒΡŽΡ‡ΠΈΡ… Ρ†Ρ–Π»ΠΎΡ‡ΠΈΡΠ΅Π»ΡŒΠ½ΠΈΡ… індСксів int, Ρ– Π½ΠΎΠ²ΠΈΠΌ ΠΊΠ»ΡŽΡ‡Π΅ΠΌ Π±ΡƒΠ΄Π΅ Ρ†Π΅ максимальнС значСння плюс 1 (Π°Π»Π΅ ΠΏΡ€ΠΈΠ½Π°ΠΉΠΌΠ½Ρ– 0). Π―ΠΊΡ‰ΠΎ Ρ†Ρ–Π»ΠΎΡ‡ΠΈΡΠ΅Π»ΡŒΠ½ΠΈΡ… індСксів int Ρ‰Π΅ Π½Π΅ існує, ΠΊΠ»ΡŽΡ‡ Π±ΡƒΠ΄Π΅ 0 (Π½ΡƒΠ»ΡŒ).

Π—Π²Π΅Ρ€Π½Ρ–Ρ‚ΡŒ ΡƒΠ²Π°Π³Ρƒ, Ρ‰ΠΎ максимальний Ρ†Ρ–Π»ΠΎΡ‡ΠΈΡΠ΅Π»ΡŒΠ½ΠΈΠΉ ΠΊΠ»ΡŽΡ‡, який Π²ΠΈΠΊΠΎΡ€ΠΈΡΡ‚ΠΎΠ²ΡƒΡ”Ρ‚ΡŒΡΡ для Ρ†ΡŒΠΎΠ³ΠΎ, Π½Π°Ρ€Π°Π·Ρ– Π½Π΅ обов’язково існує Π² масиві.. Π’Ρ–Π½ ΠΏΠΎΠ²ΠΈΠ½Π΅Π½ існувати Π² масиві лишС дСякий час Π· ΠΌΠΎΠΌΠ΅Π½Ρ‚Ρƒ ΠΎΡΡ‚Π°Π½Π½ΡŒΠΎΠ³ΠΎ ΠΏΠΎΠ²Ρ‚ΠΎΡ€Π½ΠΎΠ³ΠΎ індСксування масиву. Наступний ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Ρ–Π»ΡŽΡΡ‚Ρ€ΡƒΡ”:

<?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);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

ДСструктуризація масиву

Масиви ΠΌΠΎΠΆΠ½Π° дСструктурувати Π·Π° допомогою ΠΌΠΎΠ²Π½ΠΈΡ… конструкцій [] (ΠΏΠΎΡ‡ΠΈΠ½Π°ΡŽΡ‡ΠΈ Π· PHP 7.1.0) Π°Π±ΠΎ list(). Π¦Ρ– конструкції ΠΌΠΎΠΆΠ½Π° використовувати для дСструктурування масиву Π½Π° ΠΎΠΊΡ€Π΅ΠΌΡ– Π·ΠΌΡ–Π½Π½Ρ–.

<?php
$source_array
= ['foo', 'bar', 'baz'];

[
$foo, $bar, $baz] = $source_array;

echo
$foo; // Π²ΠΈΠ²Π΅Π΄Π΅ "foo"
echo $bar; // Π²ΠΈΠ²Π΅Π΄Π΅ "bar"
echo $baz; // Π²ΠΈΠ²Π΅Π΄Π΅ "baz"
?>

Π”Π΅ΡΡ‚Ρ€ΡƒΠΊΡ‚ΡƒΡ€ΠΈΠ·Π°Ρ†Ρ–ΡŽ масиву ΠΌΠΎΠΆΠ½Π° використовувати Ρƒ foreach для дСструктуризації Π±Π°Π³Π°Ρ‚ΠΎΠ²ΠΈΠΌΡ–Ρ€Π½ΠΎΠ³ΠΎ масиву ΠΏΡ–Π΄ час Ρ–Ρ‚Π΅Ρ€Π°Ρ†Ρ–Ρ— ΠΏΠΎ Π½ΡŒΠΎΠΌΡƒ.

<?php
$source_array
= [
[
1, 'John'],
[
2, 'Jane'],
];

foreach (
$source_array as [$id, $name]) {
// Π»ΠΎΠ³Ρ–ΠΊΠ° Ρ€ΠΎΠ±ΠΎΡ‚ΠΈ Ρ–Π· $id Ρ– $name
}
?>

Π•Π»Π΅ΠΌΠ΅Π½Ρ‚ΠΈ масиву Ρ–Π³Π½ΠΎΡ€ΡƒΠ²Π°Ρ‚ΠΈΠΌΡƒΡ‚ΡŒΡΡ, якщо Π·ΠΌΡ–Π½Π½Π° Π½Π΅ Π²ΠΊΠ°Π·Π°Π½Π°. ДСструктуризація масиву Π·Π°Π²ΠΆΠ΄ΠΈ ΠΏΠΎΡ‡ΠΈΠ½Π°Ρ”Ρ‚ΡŒΡΡ Π· індСксу 0.

<?php
$source_array
= ['foo', 'bar', 'baz'];

// ΠŸΡ€ΠΈΠ·Π½Π°Ρ”ΠΌΠΎ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚ Π· індСксом 2 Π΄ΠΎ Π·ΠΌΡ–Π½Π½ΠΎΡ— $baz
[, , $baz] = $source_array;

echo
$baz; // Π²ΠΈΠ²Π΅Π΄Π΅ "baz"
?>

ΠŸΠΎΡ‡ΠΈΠ½Π°ΡŽΡ‡ΠΈ Π· PHP 7.1.0, асоціативні масиви Ρ‚Π°ΠΊΠΎΠΆ ΠΌΠΎΠΆΠ½Π° дСструктурувати. Π¦Π΅ Ρ‚Π°ΠΊΠΎΠΆ дозволяє лСгшС Π²ΠΈΠ±ΠΈΡ€Π°Ρ‚ΠΈ ΠΏΠΎΡ‚Ρ€Ρ–Π±Π½ΠΈΠΉ Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚ Ρƒ масивах Ρ–Π· числовими індСксами, ΠΎΡΠΊΡ–Π»ΡŒΠΊΠΈ індСкс ΠΌΠΎΠΆΠ½Π° Π²ΠΊΠ°Π·Π°Ρ‚ΠΈ явно.

<?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"
?>

ДСструктуризація масиву ΠΌΠΎΠΆΠ΅ Π±ΡƒΡ‚ΠΈ використана для Π»Π΅Π³ΠΊΠΎΡ— Π·Π°ΠΌΡ–Π½ΠΈ Π΄Π²ΠΎΡ… Π·ΠΌΡ–Π½Π½ΠΈΡ…..

<?php
$a
= 1;
$b = 2;

[
$b, $a] = [$a, $b];

echo
$a; // Π²ΠΈΠ²Π΅Π΄Π΅ 2
echo $b; // Π²ΠΈΠ²Π΅Π΄Π΅ 1
?>

ЗауваТСння:

ΠžΠΏΠ΅Ρ€Π°Ρ‚ΠΎΡ€ (...) Π½Π΅ ΠΏΡ–Π΄Ρ‚Ρ€ΠΈΠΌΡƒΡ”Ρ‚ΡŒΡΡ Ρƒ призначСннях.

ЗауваТСння:

Π‘ΠΏΡ€ΠΎΠ±Π° ΠΎΡ‚Ρ€ΠΈΠΌΠ°Ρ‚ΠΈ доступ Π΄ΠΎ ΠΊΠ»ΡŽΡ‡Π° масиву, який Π½Π΅ Π±ΡƒΠ»ΠΎ Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½ΠΎ, Ρ” Ρ‚Π°ΠΊΠΎΡŽ самою, як доступ Π΄ΠΎ Π±ΡƒΠ΄ΡŒ-якої Ρ–Π½ΡˆΠΎΡ— Π½Π΅Π²ΠΈΠ·Π½Π°Ρ‡Π΅Π½ΠΎΡ— Π·ΠΌΡ–Π½Π½ΠΎΡ—: Π±ΡƒΠ΄Π΅ Π²ΠΈΠ΄Π°Π½ΠΎ повідомлСння ΠΏΡ€ΠΎ ΠΏΠΎΠΌΠΈΠ»ΠΊΡƒ рівня E_WARNING (Ρ€Ρ–Π²Π΅Π½ΡŒ E_NOTICE Π΄ΠΎ PHP 8.0.0), Ρ– Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ Π±ΡƒΠ΄Π΅ null.

ΠšΠΎΡ€ΠΈΡΠ½Ρ– Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ—

Існує Π΄ΠΎΡΠΈΡ‚ΡŒ Π±Π°Π³Π°Ρ‚ΠΎ корисних Ρ„ΡƒΠ½ΠΊΡ†Ρ–ΠΉ для Ρ€ΠΎΠ±ΠΎΡ‚ΠΈ Π· масивами. Π”ΠΈΠ²Ρ–Ρ‚ΡŒΡΡ Ρ€ΠΎΠ·Π΄Ρ–Π» "Π€ΡƒΠ½ΠΊΡ†Ρ–Ρ— для Ρ€ΠΎΠ±ΠΎΡ‚ΠΈ Π· масивами".

ЗауваТСння:

Ѐункція unset() дозволяє видаляти ΠΊΠ»ΡŽΡ‡Ρ– Π· масиву. ΠœΠ°ΠΉΡ‚Π΅ Π½Π° ΡƒΠ²Π°Π·Ρ–, Ρ‰ΠΎ масив НЕ Π±ΡƒΠ΄Π΅ ΠΏΠΎΠ²Ρ‚ΠΎΡ€Π½ΠΎ індСксований. Π―ΠΊΡ‰ΠΎ ΠΏΠΎΡ‚Ρ€Ρ–Π±Π½Π° справТня ΠΏΠΎΠ²Π΅Π΄Ρ–Π½ΠΊΠ° «видалСння Ρ‚Π° зміщСння», масив ΠΌΠΎΠΆΠ½Π° пСрСіндСксувати Π·Π° допомогою Ρ„ΡƒΠ½ΠΊΡ†Ρ–Ρ— array_values().

<?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')
?>

ΠšΠ΅Ρ€ΡƒΡŽΡ‡Π° структура foreach існує ΡΠΏΠ΅Ρ†Ρ–Π°Π»ΡŒΠ½ΠΎ для масивів. Π’ΠΎΠ½Π° Π·Π°Π±Π΅Π·ΠΏΠ΅Ρ‡ΡƒΡ” простий спосіб ΠΎΠ±Ρ…ΠΎΠ΄Ρƒ масиву.

Array do's and don'ts

Why is $foo[bar] 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:

<?php
$foo
[bar] = 'enemy';
echo
$foo[bar];
// etc
?>

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.

<?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";
}
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

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

More examples to demonstrate this behaviour:

<?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
?>

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:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants:

<?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";
?>

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:

<?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";
?>

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.

<?php

class A {
private
$B;
protected
$C;
public
$D;
function
__construct()
{
$this->{1} = null;
}
}

var_export((array) new A());
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

array (
  '' . "\0" . 'A' . "\0" . 'B' => NULL,
  '' . "\0" . '*' . "\0" . 'C' => NULL,
  'D' => NULL,
  1 => NULL,
)

These NUL can result in some unexpected behaviour:

<?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());
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

array(3) {
  ["BA"]=>
  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:

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #9 Simple array unpacking

<?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']
?>

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:

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #10 Array unpacking with duplicate key

<?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.
?>

ЗауваТСння:

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:

<?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]
?>

Examples

The array type in PHP is very versatile. Here are some examples:

<?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').
?>

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #11 Using array()

<?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();
?>

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #12 Collection

<?php
$colors
= array('red', 'blue', 'green', 'yellow');

foreach (
$colors as $color) {
echo
"Do you like $color?\n";
}

?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible by passing them by reference.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #13 Changing element in the loop

<?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);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #14 One-based index

<?php
$firstquarter
= array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

Поданий Π²ΠΈΡ‰Π΅ ΠΏΡ€ΠΈΠΊΠ»Π°Π΄ Π²ΠΈΠ²Π΅Π΄Π΅:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #15 Filling an array

<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (
false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>

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.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #16 Sorting an array

<?php
sort
($files);
print_r($files);
?>

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.

ΠŸΡ€ΠΈΠΊΠ»Π°Π΄ #17 Recursive and multi-dimensional arrays

<?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";
?>

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

<?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
?>
οΌ‹add a note

User Contributed Notes 5 notes

up
126
mlvljr ΒΆ
15 years ago
please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php).
up
76
thomas tulinsky ΒΆ
10 years ago
I think your first, main example is needlessly confusing, very confusing to newbies:

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

It should be removed.
 
For newbies:
An array index can be any string value, even a value that is also a value in the array. 
The value of array["foo"] is "bar".
The value of array["bar"] is "foo"

The following expressions are both true:
$array["foo"] == "bar"
$array["bar"] == "foo"
up
58
ken underscore yap atsign email dot com ΒΆ
18 years ago
"If you convert a NULL value to an array, you get an empty array."

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

<?php $values = search(...); ?>

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

<?php $combined = array_merge((array)$values, $other); ?>

Voila.
up
57
jeff splat codedread splot com ΒΆ
21 years ago
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
    printf("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="Windows3.1" value="Sux">
    <input type="submit" value="Click" />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )
up
38
chris at ocportal dot com ΒΆ
13 years ago
Note that array value buckets are reference-safe, even through serialization.

<?php
$x='initial';
$test=array('A'=>&$x,'B'=>&$x);
$test=unserialize(serialize($test));
$test['A']='changed';
echo $test['B']; // Outputs "changed"
?>

This can be useful in some cases, for example saving RAM within complex structures.