Type casting (also called type conversion) means converting a value from one type to another — turning the text "42" into the number 42, for example. It matters because a value read from a form, a file, or user input often arrives as text, even when it represents a number.
let input = "25";
let age = Number(input);
console.log(age); // 25
console.log(age + 5); // 30 — real addition now, not text joining<?php
$input = "25";
$age = (int) $input;
echo $age; // 25
echo $age + 5; // 30 — real addition now, not text joininginput_value = "25"
age = int(input_value)
print(age) # 25
print(age + 5) # 30 — real addition now, not text joininglet count = 7;
let message = "You have " + String(count) + " items.";
console.log(message); // "You have 7 items."<?php
$count = 7;
$message = "You have " . strval($count) . " items.";
echo $message; // "You have 7 items."count = 7
message = "You have " + str(count) + " items."
print(message) # "You have 7 items."Not every piece of text is a valid number. Converting something that isn't produces a special value called NaN ("Not a Number") rather than crashing the program.
console.log(Number("hello")); // NaN
console.log(Number("42")); // 42<?php
echo (int) "hello"; // 0 — PHP doesn't error, it just returns 0
echo (int) "42"; // 42try:
print(int("hello")) # raises ValueError: invalid literal for int()
except ValueError as e:
print(e)
print(int("42")) # 42