Arrays, Functions, Iteration, and Callbacks
Arrays and functions are the workhorses of PHP. Using them deliberately keeps transformations readable and prevents data-shape confusion.
Lists and Associative Arrays
<?php
declare(strict_types=1);
$vehicleIds = [10, 14, 21];
$customer = [
'id' => 42,
'name' => 'Example Company',
'status' => 'active',
];
echo $customer['name'];
Document complex array shapes with PHPDoc or replace them with small value objects when the same structure travels through many layers.
Iteration
<?php
declare(strict_types=1);
$totals = [12500, 18750, 9900];
$grandTotal = 0;
foreach ($totals as $totalCents) {
$grandTotal += $totalCents;
}
echo number_format($grandTotal / 100, 2);
Map, Filter, and Reduce
<?php
declare(strict_types=1);
$customers = [
['id' => 1, 'name' => 'Acme', 'active' => true],
['id' => 2, 'name' => 'Northwind', 'active' => false],
['id' => 3, 'name' => 'Contoso', 'active' => true],
];
$activeNames = array_map(
static fn (array $customer): string => $customer['name'],
array_filter(
$customers,
static fn (array $customer): bool => $customer['active'] === true
)
);
print_r(array_values($activeNames));
Readability rule: A simple
foreach is often clearer than deeply nested functional calls. Choose the form that communicates intent.Typed Functions
<?php
declare(strict_types=1);
function calculateLineTotal(int $quantity, int $unitPriceCents): int
{
if ($quantity < 1) {
throw new InvalidArgumentException('Quantity must be positive.');
}
return $quantity * $unitPriceCents;
}
Named Arguments and Defaults
<?php
declare(strict_types=1);
function createAuditEntry(
int $actorId,
string $action,
?int $recordId = null,
array $context = []
): array {
return compact('actorId', 'action', 'recordId', 'context');
}
$entry = createAuditEntry(
actorId: 7,
action: 'invoice.sent',
recordId: 214
);
Named arguments are most useful for occasional calls with several optional parameters. Avoid relying on them across public library APIs unless parameter names are treated as part of the compatibility contract.
Generators for Large Data Sets
<?php
declare(strict_types=1);
function readCsvRows(string $filename): Generator
{
$handle = fopen($filename, 'rb');
if ($handle === false) {
throw new RuntimeException('Unable to open CSV file.');
}
try {
while (($row = fgetcsv($handle)) !== false) {
yield $row;
}
} finally {
fclose($handle);
}
}
foreach (readCsvRows('customers.csv') as $row) {
// Process one row at a time without loading the entire file.
}