Getting User Input
Part of the Fundamentals section of Coddy's PHP journey — lesson 13 of 71.
As of now we stored values that we thought about in variables. Programs usually don't work this way. We receive values from an outer source, a user for example.
To get input from a user or the system we need to write:
$var = trim(fgets(STDIN));This will store the input in the variable $var — a placeholder name for any variable you choose to store the input in.
fgets(STDIN)— reads a line of input;STDINmeans standard input (typically the keyboard or a data stream)trim()— trim means to cut off; it removes extra whitespace and newlines from the beginning and end of the input
The input is always of type string. For example, if the input is 56 then
$varwill hold the string"56".
Challenge
EasyRead input from the system into the variables userName and the userAge.
If you are stuck look at the hint!
Try it yourself
<?php
$userName = ?;
$userAge = ?;
echo "Hey " . $userName . "\n";
echo "You are " . $userAge . " years old.";
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators