PHP Casting
PHP is a dynamically typed language: a variable's type is decided by the value it holds, and PHP converts between types automatically when it thinks it should. Casting is how you take control and convert a value to a specific type yourself.
Cast operators
Put the target type in parentheses in front of a value:
| Cast | Converts to |
|---|---|
(int) or (integer) |
integer |
(float) or (double) |
float |
(string) |
string |
(bool) or (boolean) |
boolean |
(array) |
array |
(object) |
stdClass object |
<?php
$price = "19.99";
var_dump((float) $price);
var_dump((int) $price); // the fraction is cut off, not rounded
var_dump((int) "42 apples"); // reads the leading number
var_dump((int) "apples"); // no leading number -> 0
var_dump((string) 3.0);
var_dump((int) -7.9);float(19.99)
int(19)
int(42)
int(0)
string(1) "3"
int(-7)
Note:
(int)truncates toward zero. If you want the nearest whole number, useround()first:(int) round(7.9)is8.
Casting to boolean
When PHP needs a true/false value — in an if, for example — it converts the value to bool. Only a short list of values become false; everything else is true.
| Falsy values |
|---|
false, 0, 0.0, -0.0 |
"" (empty string) and "0" |
[] (empty array) |
null |
<?php
$values = [
"0" => 0, "1" => 1, "-1" => -1, "0.0" => 0.0,
"''" => "", "'0'" => "0", "'0.0'" => "0.0", "' '" => " ",
"'false'" => "false", "[]" => [], "[0]" => [0], "null" => null,
];
foreach ($values as $label => $v) {
printf("%-8s => %s\n", $label, (bool) $v ? "true" : "false");
}0 => false
1 => true
-1 => true
0.0 => false
'' => false
'0' => false
'0.0' => true
' ' => true
'false' => true
[] => false
[0] => true
null => false
Surprising entries: the string "0.0", a single space, and the text "false" are all true. Only the exact string "0" and the empty string are falsy.
Casting to string and array
(string) turns true into "1" and both false and null into "". Casting a scalar to an array wraps it in a one-element array, and casting an object gives an array of its public properties.
<?php
var_dump((string) true);
var_dump((string) false);
var_dump((string) null);
print_r((array) "solo");
$point = new stdClass();
$point->x = 3;
$point->y = 4;
print_r((array) $point);
$obj = (object) ["name" => "Tam", "age" => 30];
echo $obj->name, " is ", $obj->age, "\n";string(1) "1"
string(0) ""
string(0) ""
Array
(
[0] => solo
)
Array
(
[x] => 3
[y] => 4
)
Tam is 30
Conversion functions
Besides cast operators, PHP offers functions that do the same work and can be passed as callbacks:
<?php
echo intval("0x1A", 16), "\n"; // base 16
echo intval("101", 2), "\n"; // base 2
echo floatval("1.5e3"), "\n";
echo strval(99), "\n";
var_dump(boolval("0"));
// Handy with array_map: convert every item at once
$ids = array_map('intval', ["10", "20", "30"]);
var_dump($ids);
// settype() changes the variable itself
$n = "123";
settype($n, "integer");
echo gettype($n), "\n";26
5
1500
99
bool(false)
array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
}
integer
Automatic (implicit) conversion
PHP also converts types on its own — this is called type juggling:
- Arithmetic turns numeric strings into numbers:
"5" * 2is10. - The
.operator turns numbers into strings:5 . 5is"55". - Loose comparison
==converts before comparing, so"1" == 1is true. Use===to compare type and value.
Tip: For values from users, prefer validating with
is_numeric()orfilter_var($x, FILTER_VALIDATE_INT)over blind casting — a cast never fails, it just quietly gives you0.
Test yourself
What is (int) "12.9 kg"?
13120- It throws an error
Which of these values is true when cast to bool?
"0"[]"0.0"null
What does (string) false produce?
"false""0"""(empty string)null