Arrays

Содержание
Create an array
Read by offset
Append elements
Loop over arrays

Create an array

An array stores an ordered list of values under one name. The short [] syntax builds one in a single expression, and positions count from zero. The companion page Arrays in PHP shows more array forms.

$colors = ["red", "green", "blue"]; $empty = []; var_dump(count($colors));

Read by offset

Square brackets read one element by its position: $colors[0] is the first item, $colors[2] the third. Reading a missing offset raises a warning and evaluates to null, so check long-lived data with isset first.

$colors = ["red", "green", "blue"]; echo $colors[0]; echo $colors[2];

Append elements

Empty brackets append after the last element: $cart[] = "book" adds one more item and numbers it automatically. This is how lists grow one element at a time, for example while reading rows or collecting input.

$cart = []; $cart[] = "book"; $cart[] = "pen"; echo count($cart);

Loop over arrays

The foreach loop visits every element in order and needs no counter. A classic for loop with an index works too, and fits when the position itself drives the logic.

$cart = ["book", "pen"]; foreach ($cart as $item) { echo $item; } for ($i = 0; $i < count($cart); $i++) { echo $cart[$i]; }

Next: Associative arrays

Автор статьи: Arthur Isaev

Похожие статьи
Программирование на PHP
PHP course: zero to hero in 50 lessons
What is PHP and where it runs
Install PHP 8.5 and run your first command
Your first PHP script
Comments in PHP
Variables and constants
Types in PHP
Strings in PHP
Numbers in PHP
Operators
if and else
switch and match
Ternary, null coalescing and nullsafe
Loops
Arrays
Associative arrays
Functions
Variable scope
include and require
Namespaces
Composer and autoloading
Everyday string functions
Dates and time
JSON in PHP
Reading and writing files
Errors: read, reproduce, fix
Classes and objects
Constructors and promotion
Inheritance
Interfaces and traits
Enums
Magic methods
Attributes
Exceptions
Strict types
Closures and arrow functions
Generators with yield
Forms: GET and POST
HTTP: headers and status codes
Cookies
Sessions
Login with sessions
JSON REST endpoint
Database with PDO
Uploads and .htaccess
Lint like a pro
Clean functions
Debugging
Modern PHP tour: 5 to 8.4
PHP 8.5 for busy developers
Hero roadmap: the whole course on one page

Поиск по сайту

Канал @aofeed Чат @aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: