php · level 1 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Pretend a visitor typed it, and keep it in a box.
Programs often need : information from outside, like a name a visitor types into a website. Later you will learn how real websites collect it. For now, you play the visitor.
Put each pretend answer in a variable at the top, like $typed_name = "Ravi";. The rest of the program only uses the variable, so it works the same whatever the visitor typed.
To your program, change the typed values and run it again. A good program works for every answer, not only the first one you tried.
<?php
$typed_name = "Ravi";
$typed_snack = "popcorn";
echo "Welcome, " . $typed_name . "!\n";
echo "One " . $typed_snack . " coming up.\n"; Starting each pretend answer's name with $typed_ shows where the value came from.
guess first
The visitor changed their mind. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$typed_town = "Leeds";
echo "Weather for " . $typed_town . "\n";
$typed_town = "York";
your turn
Your turn. Be the visitor.
Pretend you are the visitor. Type a name and a favourite colour in the blanks and run it. Then change them and test it again.
fix it
The greeting came too early. Can you fix it?
- Read the error:
Undefined variable $typed_name. But the box is right there on line 3. Or is it? - PHP runs from the top. When line 2 runs, nothing has been put in the box yet.
- Move the line
$typed_name = "Zoe";above theecholine, then press run.
nailed it
your program is ready for visitors. :D
- Pretend input goes in a variable at the top.
- Fill a box before you use it.
- Test with different values to check it always works.
new words in your collection
- input
- test
This lesson isn’t saved. A free account remembers every lesson you finish.