Arrays Intro
Arrays in PHP
PHP has a single array type that can behave like a list (indexed) or a map (associative). This is flexible, but it also means you must be disciplined about how you structure data.
Indexed Arrays (Lists)
Indexed arrays use numeric keys (0, 1, 2...). They are perfect for ordered lists.
<?php $tags = ['php', 'mysql', 'security']; echo $tags[0]; // php
Associative Arrays (Key/Value)
Associative arrays use string keys and are great for representing structured data like configs and DTO-like shapes.
<?php $user = [ 'id' => 1, 'name' => 'Ozan', 'role' => 'admin', ]; echo $user['name'];
Mixed Keys (Avoid When Possible)
PHP allows mixing numeric and string keys. This flexibility can create confusing data shapes, so try to keep structures consistent.
<?php $mixed = [ 'title' => 'PHP', 0 => 'first', ];
Iterating Arrays
Use foreach for most loops. It is readable and safe.
<?php
foreach ($user as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
Production Tip
When arrays represent “data contracts” (request payloads, DB rows, API responses), keep shapes consistent and validate keys. For complex domains, prefer typed objects/DTOs to reduce runtime surprises.