PHP 8 Beginner Language Basics · 7 min read

PHP Associative Arrays and Nested Records

Lesson 10 of 43 in the PHP 8 learning path.

How do I store a student record in an associative array?

An associative array maps string keys to values, which is enough for one student record before you promote it to a class. The sample stores student_id, name, track, and a nested grades array with html and php scores. You read a top-level field with $student["name"] and a nested score with $student["grades"]["php"]. The keys are part of the contract. A typo such as $student["grade"] is a different slot, and on PHP 8 a missing key warns and behaves as null when you read it without a guard.

Arrays are values. Assigning $copy = $student and then changing the copy leaves the original record alone once either side is written. That makes an array a reasonable return type from a repository method that loads one row. When the record grows behavior, such as a passing rule or a validated constructor, a class is the clearer model.

Syntax & Parameters

Syntax
$student = ['student_id' => '2026-0142', 'grades' => ['php' => 88]];
$student['grades']['php']

Example

src/Roster.php
<?php

declare(strict_types=1);

/**
 * @return array{student_id: string, name: string, track: string, grades: array{html: int, php: int}}
 */
function studentRecord(): array
{
    return [
        'student_id' => '2026-0142',
        'name' => 'Amina Cruz',
        'track' => 'web',
        'grades' => [
            'html' => 92,
            'php' => 88,
        ],
    ];
}

/**
 * @param array{student_id: string, name: string, track: string, grades: array{html: int, php: int}} $student
 */
function rosterLine(array $student): string
{
    $php = $student['grades']['php'];
    $html = $student['grades']['html'];

    return $student['name']
        . ' (' . $student['student_id'] . ', ' . $student['track'] . ')'
        . ' html=' . $html
        . ' php=' . $php;
}

$student = studentRecord();
$copy = $student;
$copy['track'] = 'data';

echo 'name=' . $student['name'] . "\n";
echo 'id=' . $student['student_id'] . "\n";
echo 'track=' . $student['track'] . "\n";
echo 'copy_track=' . $copy['track'] . "\n";
echo 'html=' . $student['grades']['html'] . "\n";
echo 'php=' . $student['grades']['php'] . "\n";
echo 'line=' . rosterLine($student) . "\n";

Expected Output

name=Amina Cruz
id=2026-0142
track=web
copy_track=data
html=92
php=88
line=Amina Cruz (2026-0142, web) html=92 php=88

Line-by-Line Walkthrough

  1. declare(strict_types=1) checks the array parameter on rosterLine() for calls in this file. The key shape is documented in the docblock.
  2. studentRecord() returns one associative array with student_id, name, track, and a nested grades array.
  3. The nested grades array uses html and php as keys and stores the two quiz scores as ints.
  4. rosterLine() reads the nested scores through $student["grades"]["php"] and $student["grades"]["html"].
  5. The returned sentence includes the name, the id, the track, and both scores so a roster row is one string.
  6. $copy = $student copies the record. Setting $copy["track"] to data does not change the original track.
  7. The name and id echoes read top-level keys on the original record.
  8. The track echo stays web, and copy_track prints data, which shows the two arrays diverged.
  9. The html and php echoes read the nested ints from the original record.
  10. rosterLine() prints the combined roster sentence from those same keys.

Common Pitfalls & Security

Associative arrays are flexible, and that flexibility is how a missing grade key becomes a warning in the middle of a report. Decide the keys, document them, and read them in one helper so a typo has a single place to fail. Arrays do not enforce types of nested values. A string stored under grades.php will print and then break a later int parameter.

  • A missing key warns on PHP 8 and yields null. $student["grades"]["php"] needs the nested array to exist. Guard with isset() when the field is optional.
  • Numeric strings and ints are different keys only when they are not cast. The key "8" and the key 8 collide because PHP casts numeric string keys to ints. Use a prefix such as student_id for identifiers.
  • Copy-on-write means $copy = $student is safe for a local edit. A function that receives the array and changes a key does not change the caller unless it returns the array or accepts it by reference.
  • Unsafe anti-pattern (do not ship): echo $student["name"]; into HTML. Encode the name with htmlspecialchars. The array does not escape anything.
  • Building SQL from $student["name"] with concatenation is SQL injection (SQLi). Pass the field as a bound parameter.
  • A public bag of untyped keys grows until no caller agrees on the shape. Move a stable record to a class with a constructor when you add rules.

Best Practices & Modern Standards

On PHP 8.3, document array shapes with an array{} docblock or return a small readonly object when the record is part of the grade-book core. Keep list arrays and associative records visually distinct: lists use 0, 1, 2, and records use names. Nested grades stay in their own array so a new subject is a new key instead of another top-level field.

Return the array from a function instead of building it in the template. The template, or a later JSON encoder, then reads known keys. Validate types when the array crosses a boundary, such as a decoded JSON body, because the array itself will accept any value under any key.

Real-World Use

The enrollment roster keeps one array per student while the term setup is still small: id 2026-0142, name Amina Cruz, track web, and grades for html and php. The report page reads those keys to print a line, and a preview copy can switch the track to data without rewriting the stored record. When the passing rule needs a method, the same fields move into a Student class.

Frequently Asked Questions

How do I read a nested grade?

Use two keys: $student["grades"]["php"]. The first key returns the inner array, and the second returns the int. Both levels have to exist.

Does $copy = $student share later edits?

No. Assignment copies the array value, with copy-on-write behind the scenes. The sample sets the copy track to data and the original track stays web.

What happens if the key is missing?

PHP 8 warns and the read evaluates as null. Check with isset($student["grades"]["php"]) or the null coalescing operator before you treat the score as an int.

When should this become a class?

When you need validation, a passing rule, or a stable set of fields that should not be renamed by accident. An array is a fine record for a short script and a weak contract for a large grade book.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…