Back to PHP tutorials
Basic15 min read

Arrays & Functions

Master PHP arrays, higher-order array functions, and function scope patterns.

Indexed and Associative Arrays

PHP arrays are ordered maps usable as lists or dictionaries. Create with [] or array(). Keys can be integers or strings; append with $arr[] = value.

Multidimensional arrays model tables and trees. json_encode and json_decode interchange arrays with JSON for APIs.

array_is_list detects sequential integer keys—useful when validating JSON arrays.

  • Use array spread ...$arr to merge arrays in PHP 7.4+
  • Destructure with [$a, $b] = $tuple
  • Avoid referencing arrays without isset on optional keys
$user = [
    'id' => 1,
    'name' => 'Ada',
    'tags' => ['admin', 'beta'],
];

Array Functions

array_map transforms elements; array_filter selects; array_reduce aggregates. array_column extracts fields from rows of associative arrays.

sort, usort, and array_multisort order data. array_unique deduplicates; array_merge combines—know reindexing behavior for numeric keys.

Leverage collections in Laravel when frameworks provide fluent chaining atop these primitives.

  • Preserve keys with array_map when keys matter
  • Use spaceship operator <=> in usort comparators
  • Consider generator functions for large datasets
$prices = array_map(fn($p) => $p * 1.2, $products);
$active = array_filter($users, fn($u) => $u['active']);

Scope and Closures

Variables default to function scope. global keyword and $GLOBALS access globals—prefer dependency injection instead.

Static variables inside functions retain state between calls—use cautiously for caches with TTL elsewhere.

Arrow functions fn() capture variables by value automatically from parent scope for concise callbacks.

  • Inject dependencies rather than reading superglobals in logic
  • Use use (&$ref) sparingly for by-reference closure capture
  • Name closures assigned to variables when stack traces matter

Get In Touch


Ready to discuss your next project? Drop me a message.