PHP does not require (or support) explicit type definition in
variable declaration; a variable's type is determined by the
context in which that variable is used. That is to say, if you
assign a string value to variable $var,
$var becomes a string. If you then assign an
integer value to $var, it becomes an
integer.
An example of PHP's automatic type conversion is the addition
operator '+'. If any of the operands is a float, then all
operands are evaluated as floats, and the result will be a
float. Otherwise, the operands will be interpreted as integers,
and the result will also be an integer. Note that this does NOT
change the types of the operands themselves; the only change is in
how the operands are evaluated.
<?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?>
If you wish to force a variable to be evaluated as a certain type,
see the section on Type
casting. If you wish to change the type of a variable, see
settype().
If you would like to test any of the examples in this section, you
can use the var_dump() function.
Note:
The behaviour of an automatic conversion to array is currently
undefined.
Also, because PHP supports indexing into strings via offsets using
the same syntax as array indexing, the following example holds true
for all PHP versions:
<?php $a = 'car'; // $a is a string $a[0] = 'b'; // $a is still a string echo $a; // bar ?>