Tutorials Logic, IN info@tutorialslogic.com

PHP Arrays: Lists, Maps, Nested Data, and Transformations

PHP Ordered Maps

A PHP array is an ordered map whose key conversion, list shape, copy-on-write behavior, null-aware access, mutation, merge, sorting, callback, reference, and serialization rules all affect application correctness.

Reliable code validates shape, separates lists from dictionaries, chooses collision policy explicitly, avoids lingering foreach references, bounds nested data, and streams datasets that should not live entirely in memory.

Lists and Maps

Course List and Record

Course List and Record
<?php
$topics = ['syntax', 'forms', 'pdo'];
$lesson = [
    'title' => 'PHP Arrays',
    'minutes' => 25,
    'published' => true,
];

echo $topics[1] . ': ' . $lesson['title'];
Output
forms: PHP Arrays

Safe Key Access

Use ?? when missing and null should share a default. Use array_key_exists() when null is meaningful. Use isset() when the key must exist and be non-null.

Do not suppress undefined-key warnings. They usually reveal unhandled input or an inconsistent shape.

Read Optional Configuration

Read Optional Configuration
<?php
$config = ['timezone' => 'Asia/Kolkata', 'cache' => null];

$timezone = $config['timezone'] ?? 'UTC';
$hasCacheSetting = array_key_exists('cache', $config);

echo $timezone . ' / ' . ($hasCacheSetting ? 'configured' : 'missing');
Output
Asia/Kolkata / configured

Map, Filter, and Reduce

array_map() transforms values, array_filter() keeps matching values, and array_reduce() combines a collection into one result.

Filter and Format Scores

Filter and Format Scores
<?php
$scores = [48, 72, 91, 63];
$passing = array_filter($scores, fn (int $score): bool => $score >= 60);
$labels = array_map(fn (int $score): string => "{$score}%", $passing);

echo implode(', ', $labels);
Output
72%, 91%, 63%

Nested Records

A list of associative arrays works for database rows or decoded JSON. When every record has behavior, invariants, or many required fields, a typed object is often clearer.

Group Lessons by Status

Group Lessons by Status
<?php
$lessons = [
    ['title' => 'Syntax', 'status' => 'done'],
    ['title' => 'Forms', 'status' => 'next'],
    ['title' => 'PDO', 'status' => 'next'],
];

$grouped = [];
foreach ($lessons as $lesson) {
    $grouped[$lesson['status']][] = $lesson['title'];
}

echo implode(', ', $grouped['next']);
Output
Forms, PDO

Array Traps

  • array_filter() preserves keys; call array_values() when a new zero-based list is required.
  • The + operator performs array union and is not the same as array_merge().
  • Sorting functions differ in whether they preserve keys.
  • A foreach value copy does not update the original array.

Ordered Map Semantics

A PHP array is an ordered map that can act as a list, dictionary, stack, queue, or tree. Keys are integers or strings after PHP key conversion rules. Numeric-looking string keys may become integers, booleans become zero or one, and null becomes an empty-string key.

Lists use consecutive integer keys starting at zero. Removing an element does not automatically reindex remaining keys. Use `array_is_list` when list shape matters and `array_values` only when intentionally discarding original keys.

Assignment copies an array using copy-on-write behavior until a value is modified, while nested objects remain object handles. A copied outer array does not clone contained objects. Define ownership of nested values before calling an array copy independent.

Use arrays for moderate in-memory data, not as an automatic substitute for typed domain objects. Fixed records benefit from named classes or value objects that validate required fields and prevent misspelled keys.

  • Understand key conversion and insertion order.
  • Distinguish list shape from arbitrary integer keys.
  • Remember that nested objects remain shared handles.
  • Use domain objects for fixed validated records.

Creation and Access

Create arrays with short syntax and choose keys deliberately. Appending with empty brackets selects the next integer key based on PHP rules; it does not fill every gap. Avoid mixing list and dictionary behavior in one structure because iteration and JSON encoding become surprising.

Accessing a missing key reports a warning under current PHP behavior and yields null in common expression contexts. Use `array_key_exists` when a present null value differs from absence; use `isset` when both absence and null should be treated as unavailable.

The null coalescing operator provides a concise default for missing or null keys without an undefined-key warning in supported access forms. Do not use it on required input. Validate required keys once and fail with field context.

Destructuring can extract positional or keyed values. Ensure the shape is known and defaults represent valid optionality. A destructuring notice is evidence of an unvalidated contract, not something to suppress.

  • Keep list and dictionary shapes separate.
  • Choose array_key_exists or isset from null semantics.
  • Use defaults only for genuinely optional keys.
  • Validate shape before destructuring.

Mutation and Merge Rules

Element assignment, append, unset, sort functions, and many array helpers mutate the array or return a new one according to their contract. Publish whether a function changes its argument, especially when references are involved. Prefer returned transformations when shared ownership would make mutation surprising.

The union operator keeps left-side keys and adds only missing right-side keys. `array_merge` overwrites string keys and reindexes numeric keys. Recursive merge functions can create nested arrays where replacement was expected. Choose one explicit duplicate-key policy for configuration and request data.

Sorting functions differ in whether they preserve keys and how values are compared. Provide a comparator for domain order, return an integer with consistent ordering, and define tie breakers. Never sort a collection merely to hide nondeterministic database ordering; request the needed order from the data source.

Removing values while iterating can complicate keys and references. Prefer `array_filter` or build a new result. If filtering must preserve list JSON shape, reindex intentionally after selection.

  • Document mutation and reference ownership.
  • Select union or merge from collision semantics.
  • Choose sort functions from key preservation needs.
  • Reindex filtered lists only when the contract requires it.

Mapping, Filtering, and Reduction

`array_map` transforms values, `array_filter` selects entries, and `array_reduce` accumulates one result. Use the function that communicates intent and keep callbacks free of hidden mutation. A foreach loop is clearer when control flow, keys, early exit, or multiple accumulators matter.

Default `array_filter` removes values considered empty, including zero and false. Supply an explicit predicate when those values are valid. Key-preservation behavior can produce non-list arrays that JSON encodes as objects, so assert the intended shape.

Callback signatures and key behavior differ among array functions. Check the official contract before assuming every callback receives value and key. Use `ARRAY_FILTER_USE_KEY` or `ARRAY_FILTER_USE_BOTH` when the filter decision requires keys.

Repeated linear search inside a loop can become quadratic. Build a lookup array keyed by stable identifiers when many membership checks use the same collection. Handle duplicate keys according to a documented policy instead of silently keeping the last value.

  • Choose transformations from the intended result.
  • Supply predicates when zero and false are valid.
  • Verify callback signatures and key preservation.
  • Build lookup maps for repeated membership tests.

References and Nested Data

A foreach loop by reference leaves the loop variable referencing the last element after iteration. Unset that variable before reusing it, or prefer ordinary value iteration. Accidentally retaining the reference can overwrite the final element in a later loop.

Nested access should validate each required level or convert raw input into a typed object. Deep string-path setters cannot infer whether a segment should be a list, dictionary, or forbidden key and can create insecure or malformed structures.

Recursive traversal needs limits for depth and total nodes. External JSON or form data can create large nested arrays that exhaust memory or time. Reject over-complex structures before recursive normalization, comparison, or merge.

Serialization preserves values under the selected format, not references, resources, closures, or every key distinction. JSON object keys are strings and PHP list shape influences array versus object output. Define a transport schema rather than exposing internal arrays directly.

  • Unset foreach reference variables immediately.
  • Replace deep untyped paths with schema-aware updates.
  • Bound nested depth and total node count.
  • Serialize through an explicit transport shape.

Array Tests and Scaling

Test empty arrays, one element, null values, zero and false, missing keys, converted numeric keys, sparse integer keys, duplicate merge keys, nested objects, sort ties, and maximum accepted size. Assert key order and list shape when consumers depend on them.

Property-based tests can verify that filtering returns only matching values, sorting preserves membership, grouping assigns every input once, and serialization respects the schema. Include malformed external arrays rather than testing only hand-built valid fixtures.

PHP arrays are flexible and memory-intensive compared with specialized structures. For large streams, process rows incrementally with generators or database cursors instead of collecting everything. Measure peak memory and stop work under a defined record limit.

Static analysis can describe array shapes and generic element types through supported annotations or language features, catching misspelled keys and mixed operations. Runtime validation remains required for request, JSON, cache, and database data.

  • Cover key conversion, null, sparse, and merge boundaries.
  • Assert list shape and ordering where observable.
  • Stream large datasets instead of materializing arrays.
  • Combine static array shapes with runtime validation.
Before you move on

Mastery Check

5 checks
  • Keep list and dictionary shapes distinct.
  • Choose isset or array_key_exists from null semantics.
  • Document mutation, sorting, and merge behavior.
  • Unset foreach reference variables after iteration.
  • Test keys, order, nesting, serialization, and size limits.

Choose the Array Operation

0 of 2 checked

Q1. Which function transforms every array value?

Q2. When is an object often clearer than an associative array?

Array Boundary

  • Missing key and null value

    isset returns false for both a missing key and a key whose value is null. Use array_key_exists when that distinction affects behavior.

Try this next

Transform a Dataset

0 of 2 completed

  1. Reduce price and quantity records into one total.
  2. Convert a list of user records into a map keyed by integer id.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.