PHP does not need (or does not support) explicit type definitions in variable definitions; The variable type is determined by the context in which the variable is used. In other words, if you assign a string value to a variable $var, $var becomes a string. If you assign an integer value to the $var, it becomes an integer.
An example of automatic type conversion for PHP is the addition operator "+". If any one operand is a floating-point number, all operands are treated as floating-point numbers, and the result is a floating-point number. Otherwise the operand is interpreted as an integer, and the result is an integer. Note that this does not change the type of the operands themselves; it only changes how the operands are evaluated and the type of the expression itself.
<?php$foo = "0"; $foo is a string (ASCII) $foo + = 2; $foo is now an integer (2) $foo = $foo + 1.3; $foo is now a floating point (3.3) $foo = 5 + "Ten Little piggies"; $foo is an integer ($foo) = 5 + "Small Pigs"; $foo is an integer (?>)
If you want to test any of the examples in this section, you can use the Var_dump () function.
Note:
The behavior of an auto-convert array is not currently defined.
In addition, because PHP supports using the same syntax as the array subscript to access the string subscript, the following example is valid in all versions of PHP:
<?php
$a = ' car '; $a is a string
$a [0] = ' B '; $a is still a string
echo $a; Bar
?>
Type casting
The type casts in PHP are very similar to those in C: precede the variables to be converted with the target type enclosed in parentheses.
<?php$foo = ten; $foo is an Integer$bar = (Boolean) $foo; $bar is a boolean?>
The allowable casts are:
(int), (integer)-Convert to Integer
(bool), (Boolean)-converts to Boolean type bool
(float), (double), (real)-Convert to float float
(string)-Convert to String
(array)-Convert array array
(object)-Convert to Object
(unset)-Convert to NULL (PHP 5)
(binary) conversion and B prefix conversion support for PHP 5.2.1 New.
Note that spaces and tabs are allowed inside the parentheses, so the following two examples function the same:
<?php
$foo = (int) $bar;
$foo = (int) $bar;
?>
Convert string literals and variables to binary strings:
<?php
$binary = (binary) $string;
$binary = B "binary string";
?>
Note:
You can place a variable in double quotation marks instead of converting a variable to a string:
<?php$foo = ten; $foo is an integer $str = "$foo"; $str is a string $fst = (string) $foo; $fst is also a string//output "They is the same" if ($fst = = = $str) {echo "They is the same";}? >
Sometimes what exactly happens when casting between types may not be obvious. See below for more information:
Convert to Boolean type
Convert to integral type
Convert to floating point type
Convert to String
Converting to arrays
Convert to Object
Convert to Resource
Convert to NULL