php · level 1 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Ask an array for its biggest, smallest and total.
hands back the biggest item in an array and the smallest. array_sum adds every item up, so a total does not always need a loop.
checks whether a value is in the array. Put the value first, then the array: in_array(19, $temps). It gives true or false, so it fits straight into an if.
To find the first item that matches a question, loop with foreach, check each item with an if, and break as soon as you find it.
<?php
$temps = [14, 19, 11, 17];
echo "Hottest: " . max($temps) . "\n";
echo "Coldest: " . min($temps) . "\n";
echo "All added up: " . array_sum($temps) . "\n";
if (in_array(19, $temps)) {
echo "We had a 19 degree day!\n";
} in_array looks for an exact match, so "Dog" with a capital D will not find "dog".
guess first
Find the first name with 3 letters. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$names = ["Al", "Ben", "Cleo", "Dee"];
foreach ($names as $name) {
if (strlen($name) === 3) {
echo "Found $name\n";
break;
}
}
your turn
Your turn. Find the first long snack.
Type three snacks. Make sure at least one has more than 5 characters, then run it to find the first long one.
fix it
There is an apple in there. Why the crash? Fix it.
- Read the error:
in_arraywanted an array second, but it got a string. Look at the order inside the brackets. in_arrayneeds the value to look for first, then the array to look in.- Swap them so line 3 says
in_array("apple", $snacks), then press run.
nailed it
you can search an array like a detective. :D
max,minandarray_sumwork on a whole array.in_array(value, array)givestrueorfalse.- Loop, check each item, and
breakwhen you find it.
new words in your collection
- in_array
- max
- min
This lesson isn’t saved. A free account remembers every lesson you finish.