Type casting means converting a value to another type on purpose. You write the target type in brackets in front of the value.
| Cast | Result |
|---|---|
(int) | integer |
(float) | float |
(string) | string |
(bool) | boolean |
(array) | array |
(object) | object |
To integer
<?php
var_dump((int) "42");
var_dump((int) 9.99);
var_dump((int) "12 apples");
var_dump((int) "apples");
var_dump((int) true);
int(42)
int(9)
int(12)
int(0)
int(1)
Two things to notice. Casting a float to an int cuts off the decimals (it does not round). And text that does not start with a number becomes 0.
To float and string
<?php
var_dump((float) "3.5");
var_dump((string) 25);
var_dump((string) true);
var_dump((string) false);
float(3.5)
string(2) "25"
string(1) "1"
string(0) ""
To boolean
<?php
var_dump((bool) 0);
var_dump((bool) 1);
var_dump((bool) "");
var_dump((bool) "0.0");
bool(false)
bool(true)
bool(false)
bool(true)
To array
Casting a single value to an array wraps it in a list.
<?php
print_r((array) "hello");
Array
(
[0] => hello
)
Cast functions
intval(), floatval() and strval() do the same as the casts and are handy as callbacks.
<?php
print_r(array_map("intval", ["1", "2", "3"]));
Array
(
[0] => 1
[1] => 2
[2] => 3
)
A cast does not validate
(int) "abc" quietly gives 0, which could be mistaken for real input. For user data, validate first (for example with filter_var($v, FILTER_VALIDATE_INT)), then cast.