Although PHP is a weakly typed language, there are occasions when it’s useful to consider a value as a specific type. The casting operators, (int), (float), (string), (bool), (array), (object), and (unset), allow you to force a value into a particular type
Table of PHP casting operators
Operator | Synonymous operators | Changes type to |
---|---|---|
(int) | (integer) | Integer |
(bool) | (boolean) | Boolean |
(float) | (double), (real) | Floating point |
(string) | String | |
(array) | Array | |
(object) | Object | |
(unset) | NULL |
Casting affects the way other operators interpret a value rather than changing the value in a variable. For example, the code:
$a = “5”;
$b = (int) $a;
assigns $b the integer value of $a; $a remains the string “5”. To cast the value of the variable itself, you must assign the result of a cast back to the variable:
$a = “5”
$a = (int) $a; // now $a holds an integer
Not every cast is useful. Casting an array to a numeric type gives 1, and casting an array to a string gives “Array” (seeing this in your output is a sure sign that you’ve printed a variable that contains an array)
Casting an object to an array builds an array of the properties, thus mapping property names to values:
class Person
{
var $name = “Fred”;
var $age = 35;
}
$o = new Person;
$a = (array) $o;
print_r($a);
Array (
[name] => Fred
[age] => 35
)
You can cast an array to an object to build an object whose properties correspond to the array’s keys and values. For example:
$a = array(‘name’ => “Fred”, ‘age’ => 35, ‘wife’ => “Wilma”);
$o = (object) $a;
echo $o->name;
Fred
Keys that are not valid identifiers are invalid property names and are inaccessible when an array is cast to an object, but are restored when the object is cast back to an array