Summary - Array basics
Combine array creation, access and iteration to build a weekly temperature list.
Summary - Array basics
In this group you learned the basics of arrays. You create an array with [] or array(); you access elements with $arr[index] where the index starts at 0.
count() gives the element count and print_r() prints the full array in a readable form. To walk an array you use for (by index) or foreach (by element). Now you will combine these in a weekly temperature list task.
Exercise Print the weekly temperatures
Walk the $temperatures = [22, 25, 28, 24, 21, 26, 30]; array with foreach and print each temperature on its own line with echo. Append "\n" to each line. Expected output: 22, 25, 28, 24, 21, 26, 30.
Show example solution
<?php
$temperatures = [22, 25, 28, 24, 21, 26, 30];
// Print the temperatures with foreach
foreach ($temperatures as $temp) {
echo $temp . "\n";
}
Example solution:
<?php
$temperatures = [22, 25, 28, 24, 21, 26, 30];
// Print the temperatures with foreach
foreach ($temperatures as $temp) {
echo $temp . "\n";
}
Finding the largest value with for
To find the largest value in an array, use for and if together. First set $max to the first element, then compare each element to $max.
Example shape: start with $max = $temperatures[0];, walk with for ($i = 1; $i < count($temperatures); $i++), and update with if ($temperatures[$i] > $max) { $max = $temperatures[$i]; }. At the end echo $max; gives the largest value.
Exercise Find the hottest day
Find the largest temperature in $temperatures = [22, 25, 28, 24, 21, 26, 30]; with a for loop and an if. Initialize $max with the first element, walk from 1 to count, and when $temperatures[$i] > $max update $max. At the end print with echo $max . "\n";. Expected output: 30.
Show example solution
<?php
$temperatures = [22, 25, 28, 24, 21, 26, 30];
// Find the hottest day
$max = $temperatures[0];
for ($i = 1; $i < count($temperatures); $i++) {
if ($temperatures[$i] > $max) {
$max = $temperatures[$i];
}
}
echo $max . "\n";
Example solution:
<?php
$temperatures = [22, 25, 28, 24, 21, 26, 30];
// Find the hottest day
$max = $temperatures[0];
for ($i = 1; $i < count($temperatures); $i++) {
if ($temperatures[$i] > $max) {
$max = $temperatures[$i];
}
}
echo $max . "\n";
Test yourself
-
Which function returns the element count of an array?
- count()
- print_r()
- echo
- isset()
Show answer
count() — Correct. count() returns the number of elements in an array.
-
Match each concept to its meaning
- []
- Short array syntax
- $arr[0]
- First element
- count()
- Element count
- foreach
- Walk by element