Foundations
Arrays
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
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";
$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
$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
$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
$scoresstarts as82,91, and76.$bonusstarts at5.$firstScore = $scores[0]reads82.$adjustedScore = $scores[1] + $bonusadds91 + 5.- The program prints
first=82andadjusted=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.