bhylu.com

Advertisements

PHP Multidimensional Arrays

Nested arrays can represent a small collection of records. Give each level a stable meaning so a missing field is not confused with an unrelated nesting mistake.

How it works

Here each outer list item is a loan, and each loan has an id, item and quantity. Iteration preserves the connection between an item name and its count. Accessing a deeply nested key without validation assumes every intermediate value has the expected shape. At an external boundary, validate the structure once before passing the data into a calculation or view.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l nested-records.php
php nested-records.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · nested-records.php

<?php
declare(strict_types=1);

$loans = [["id"=>21,"item"=>"Rake","quantity"=>2],["id"=>22,"item"=>"Saw","quantity"=>1]];
$total = 0;
foreach ($loans as $loan) {
    $total += $loan["quantity"];
    echo $loan["id"], ": ", $loan["item"], "\n";
}
echo "Units: ", $total, "\n";

Expected result

21: Rake
22: Saw
Units: 3

The sum counts units, not loans: there are two loans but three borrowed tools. Reading the ID and item from the same record keeps the relationship visible. This example uses a trusted fixture; a request or decoded JSON document still needs required-field, type and range checks.

Check the official PHP manual for detailed version and API contracts.