Menu
Coddy logo textTech

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:

CastExplanation
(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 icon

Challenge

Your task:

  1. Read the first number from input and store it in a variable
  2. Read the second number from input and store it in another variable
  3. Convert the second variables to int type
  4. Calculate the multiplication of these two numbers
  5. 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 string

Casting 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" becomes 5
  • "bb" becomes 0
  • "4.5" becomes 4

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;

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals