๐ฏ By the end of this lesson you canโฆ
- Read input with readline()
- Convert and trim input
- Build an interactive calculator
1<?php2$name = trim(readline());3$age = (int) readline();4echo "Hi $name! Next year you will be " . ($age + 1) . ".\n";
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};
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.
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.
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}
1<?php2$name = " Asha ";3echo strlen($name), " ", strlen(trim($name));
๐ Key takeaways
readline()returns a string (without the newline).- Convert with
(int),(float); trim withtrim(). - 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.