Arrays keep related values in order and let code read values by index.

array index Array indexes start at zero, so `$scores[0]` reads the first value.

Arrays

bonus
arrays.php
Replay: real traced execution (multi-file project)
<?php
$scores = [82, 91, 76];
$bonus = 5;
$firstScore = $scores[0];
$adjustedScore = $scores[1] + $bonus;

echo "first=" . $firstScore . "\n";
echo "adjusted=" . $adjustedScore . "\n";
<?php
$scores = [82, 91, 76];
$bonus = 0;
$firstScore = $scores[0];
$adjustedScore = $scores[1] + $bonus;

echo "first=" . $firstScore . "\n";
echo "adjusted=" . $adjustedScore . "\n";
<?php
$scores = [82, 91, 76];
$bonus = 10;
$firstScore = $scores[0];
$adjustedScore = $scores[1] + $bonus;

echo "first=" . $firstScore . "\n";
echo "adjusted=" . $adjustedScore . "\n";
  1. $scores ← Array, $bonus ← 5, $firstScore ← 82, $adjustedScore ← 96

    1<?php2$scores→ Array = [82, 91, 76];3$bonus→ 5 = 5; //@bonus=0, 104$firstScore→ 82 = $scores[0]82;5$adjustedScore→ 96 = $scores[1]91 + $bonus5;67echo "first=" . $firstScore82 . "\n";8echo "adjusted=" . $adjustedScore96 . "\n";
    outputfirst=82
    adjusted=96
  1. $scores ← Array, $bonus ← 0, $firstScore ← 82, $adjustedScore ← 91

    1<?php2$scores→ Array = [82, 91, 76];3$bonus→ 0 = 0;4$firstScore→ 82 = $scores[0]82;5$adjustedScore→ 91 = $scores[1]91 + $bonus0;67echo "first=" . $firstScore82 . "\n";8echo "adjusted=" . $adjustedScore91 . "\n";
    outputfirst=82
    adjusted=91
  1. $scores ← Array, $bonus ← 10, $firstScore ← 82, $adjustedScore ← 101

    1<?php2$scores→ Array = [82, 91, 76];3$bonus→ 10 = 10;4$firstScore→ 82 = $scores[0]82;5$adjustedScore→ 101 = $scores[1]91 + $bonus10;67echo "first=" . $firstScore82 . "\n";8echo "adjusted=" . $adjustedScore101 . "\n";
    outputfirst=82
    adjusted=101

Follow the Array

  1. $scores starts as 82, 91, and 76.
  2. $bonus starts at 5.
  3. $firstScore = $scores[0] reads 82.
  4. $adjustedScore = $scores[1] + $bonus adds 91 + 5.
  5. The program prints first=82 and adjusted=96. | bonus | first score | adjusted score | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |

Exercise: arrays.php

Reproduce first=82 and adjusted=96, then try bonus 0 and 10 and predict each adjusted score before running it.