Cast to Different Types
Part of the Fundamentals section of Coddy's PHP journey — lesson 14 of 71.
To convert the input to a different type, we need to cast. To cast a string to an int (a whole number), we will write:
$var = trim(fgets(STDIN));
$var = (int)$var;Or in one line:
$var = (int)trim(fgets(STDIN));If the input is a number, i.e. 5, 4, 54 then $var will hold a number. If the input contains an invalid number: 5ab, bb, akt, etc. then PHP will convert what it can (e.g., "5ab" becomes 5, "bb" becomes 0).
Here is a table that shows how to cast to different types:
| Cast | Explanation |
| (int) | Convert to a whole number |
| (float) | Convert to a real number |
| (bool) | Convert to a boolean |
| (string) | Convert to a string |
It is important to use the right type because it can affect the output.
Adding two strings will result in:
"5" + "5" = 10(PHP converts strings to numbers for arithmetic)
Concatenating two strings will result in:
"5" . "5" = “55”
Challenge
Your task:
- Read the first number from input and store it in a variable
- Read the second number from input and store it in another variable
- Convert the second variables to int type
- Calculate the multiplication of these two numbers
- Print the result
Example:
If the inputs are 2 and 4.5, your program should output 8 because 4.5 is converted into 4
Cheat sheet
To cast (convert) a value to a different type in PHP, use the casting syntax:
$var = (int)$value; // Cast to integer (whole number)
$var = (float)$value; // Cast to float (real number)
$var = (bool)$value; // Cast to boolean
$var = (string)$value; // Cast to stringCasting input from STDIN to an integer:
$var = trim(fgets(STDIN));
$var = (int)$var;Or in one line:
$var = (int)trim(fgets(STDIN));When casting strings to integers, PHP converts what it can. Invalid characters are ignored:
"5ab"becomes5"bb"becomes0"4.5"becomes4
Type affects operations:
- Arithmetic with strings:
"5" + "5" = 10(PHP auto-converts to numbers) - Concatenation:
"5" . "5" = "55"
Try it yourself
<?php
// Read input
$firstNumber = ?;
$secondNumber = ?;
// Convert the $secondNumber to int
// Calculate the result
$result = ?;
echo $result;
?>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