PHP Automatic Type Conversion

Description

PHP automatically converts one type of variable to another whenever possible.

Example 1


<?PHP//from   w  w  w.  j a va  2 s . co m
$mystring = "12"; 
$myinteger = 20; 
print $mystring + $myinteger; 
?>

The code above generates the following result.

That script will output 32.

Example

Converting from a boolean to a string will produce a 1 if the boolean is set to true, or an empty string if false.

Consider this script:


<?PHP/*from  www . java 2  s  . co  m*/
$bool = true; 
print "Bool is set to $bool\n"; 
$bool = false; 
print "Bool is set to $bool\n"; 
?>

The code above generates the following result.

We can solve this problem by typecasting.


<?PHP//ww  w  .  j  av a  2 s .  c om
$bool = true; 
print "Bool is set to $bool\n"; 
$bool = false; 
print "Bool is set to "; 
print (int)$bool; 
?>

The code above generates the following result.

This time the script outputs 1 and 0 as we wanted.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone