Saturday, December 8, 2007

Data Types

Data Types

While PHP is very flexible with variables and allows you to treat them as text values one moment and numbers the next, it does have a set of data types that it assigns when dealing with a variable. The eight types are as follows:

  • string

  • integer

  • double

  • array

  • boolean

  • object

  • resource

  • unknown

double is PHP's word for a floating-point value; it stores floating-point values with "double precision". Since PHP doesn't have "single precision" floating-point numbers, this distinction isn't really significant.

You can check on what type PHP has assigned to a variable by using the gettype() function:

       $Variable = "This is some text";
echo(gettype($Variable));
?>

This will print out string.

You can also use the related function settype() to explicitly set the type. It requires the variable name followed by the type you wish to set it to:

    $Variable = "2";
settype($Change, integer);
echo(gettype($Change));
echo($Change);

Casting

PHP also has casting operators, which allow you to tell PHP to treat a value of one type as if it were of another type. The casting operators are the name of the type to which you want to cast the data, enclosed in parentheses:

  • (string)

  • (integer)

  • (double)

  • (boolean)

There are also abbreviated versions of some of these operators:

  • (int)

  • (bool)

They are used as follows:

       $a = "123.456";
echo((int)$a);
?>

This prints out 123 because PHP has converted the string value, 123.456, into a whole integer.

PHP also has some interesting behavior when it performs conversions. Take a look at the following code:

    $Change = "2 Coffee Candies";
settype($Change, integer);
echo(gettype($Change));
echo($Change);

Instead of causing an error, this program will actually display integer and 2. For the text to become an integer, it has to lose the extraneous information that can't be turned into a number, but PHP finds the number at the start of the string and uses that. You can procure this explicit type-conversion behavior without settype():

    $Variable1 = 3;
$Variable2 = "2 Coffee Candies";
$SumTotal = $Variable1 + $Variable2;

The result of this sum would be 5 because PHP recognizes the addition operation, and understands that's your intention. It performs an integer conversion on $Variable2 and then adds the contents of the two variables together. In other programming languages this would quite likely cause an error, but because of PHP's weak typing, you're allowed to get away with it.

To understand properly how PHP makes these decisions, let's look at how it treats operators.

No comments: