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.
<?php
$topics = ['syntax', 'forms', 'pdo'];
$lesson = [
'title' => 'PHP Arrays',
'minutes' => 25,
'published' => true,
];
echo $topics[1] . ': ' . $lesson['title'];
forms: PHP Arrays
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.
<?php
$config = ['timezone' => 'Asia/Kolkata', 'cache' => null];
$timezone = $config['timezone'] ?? 'UTC';
$hasCacheSetting = array_key_exists('cache', $config);
echo $timezone . ' / ' . ($hasCacheSetting ? 'configured' : 'missing');
Asia/Kolkata / configured
array_map() transforms values, array_filter() keeps matching values, and array_reduce() combines a collection into one result.
<?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);
72%, 91%, 63%
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.
<?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']);
Forms, PDO
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.
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.
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.
`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.
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.
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.
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.