PHP Tutorial · PHP Basics · Lesson 10 of 38
PHP Type Casting
Convert between types with casts and conversion functions.
Casting
Put the target type in parentheses before a value:
<?php
var_dump((int) "42");
var_dump((int) "12abc");
var_dump((float) "3.14");
var_dump((string) 99);
var_dump((bool) "0", (bool) "false", (bool) "");
var_dump((array) "one");
Output
int(42)
int(12)
float(3.14)
string(2) "99"
bool(false)
bool(true)
bool(false)
array(1) {
[0]=>
string(3) "one"
}Numeric strings
PHP 8 is stricter about strings that only start with a number. (int) still reads leading digits, but arithmetic on a string like "12abc" triggers a warning. Validate input with is_numeric() or filter_var() before converting:
<?php
$inputs = ["42", "4.5", "abc", "10e2"];
foreach ($inputs as $in) {
echo $in, " → ", is_numeric($in) ? "numeric" : "not numeric", "\n";
}
var_dump(filter_var("123", FILTER_VALIDATE_INT));
var_dump(filter_var("12.3", FILTER_VALIDATE_INT));
Output
42 → numeric 4.5 → numeric abc → not numeric 10e2 → numeric int(123) bool(false)
Test yourself
What does (bool) "0" evaluate to?
truefalsenull0
Show answer
Answer: false
In PHP, the string "0" is falsy — one of the language's classic gotchas.