LESSON 05 / 05

Reading Input

On the command line PHP reads input with readline() and fgets(STDIN). Convert it, validate it and build interactive programs.

๐ŸŽ“Beginnerlevel
โฑ๏ธ25 minto finish
โœ๏ธ2activities

๐Ÿ“‚ PHP Basics๐Ÿท๏ธ PHP basics

๐ŸŽฏ By the end of this lesson you canโ€ฆ

  • Read input with readline()
  • Convert and trim input
  • Build an interactive calculator
๐Ÿ˜ PHP greet.php ๐Ÿ‘† Tap a line to explain it
1<?php2$name = trim(readline());3$age = (int) readline();4echo "Hi $name! Next year you will be " . ($age + 1) . ".\n";
๐Ÿ˜ PHP bmi.php ๐Ÿ‘† Tap a line to explain it
1<?php2$kg = (float) readline("Weight (kg): ");3$m = (float) readline("Height (m): ");4$bmi = round($kg / ($m ** 2), 1);5echo "BMI: $bmi\n";6echo match (true) {7    $bmi < 18.5 => "Underweight",8    $bmi < 25 => "Healthy",9    default => "Overweight",10};
๐Ÿ› ๏ธ Split the bill

Read the bill total and the number of friends. Print each share with 2 decimals: Each pays โ‚น<share>.

Input is always text

readline() gives you a string, even when someone types a number. PHP often converts it for you in maths, but comparisons and var_dump show the truth โ€” so convert on purpose, right where you read it.

๐Ÿ˜ PHP convert.php ๐Ÿ‘† Tap a line to explain it
1<?php2$a = readline();3var_dump($a);4$n = (int) $a;5$price = (float) readline();6var_dump($n, $price);7echo $n * $price, "\n";

Check before you trust

People type anything. is_numeric() answers โ€œdoes this text look like a number?โ€, so you can refuse bad input with a friendly message instead of a wrong answer.

๐Ÿ˜ PHP safe-divide.php ๐Ÿ‘† Tap a line to explain it
1<?php2$a = readline();3$b = readline();4if (!is_numeric($a) || !is_numeric($b)) {5    echo "Please type numbers only.\n";6} elseif ((float) $b == 0) {7    echo "Can't divide by zero.\n";8} else {9    echo $a / $b, "\n";10}
๐Ÿ”ฎ What will this display?
Someone typed a name with spaces around it. What does this print?
1<?php2$name = " Asha ";3echo strlen($name), " ", strlen(trim($name));

๐Ÿ“Œ Key takeaways

  • readline() returns a string (without the newline).
  • Convert with (int), (float); trim with trim().
  • On websites, input comes from forms instead ($_GET / $_POST) โ€” Phase 4.

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.