Sunday, June 30, 2013

PHP data types



In PHP we have 8 primitive data types. They are categorized into 3 basic categories – scalar, compound, and special. It’s also important to note that PHP is a dynamically typed language.
 
Scalar types
·         boolean
·         integer
·         float
·         string

Compound types
·         array
·         object

Special types
·         resources
·         NULL
Unlike in languages like Java, C or Visual Basic, in PHP you do not provide an explicit type definition for a variable. A variable's type is determined at runtime by PHP. If you assign a string to a variable, it becomes a string variable.

Boolean values:
In PHP the boolean data type is a primitive data type having one of two values: True or False. This is a fundamental data type. Very common in computer programs.

Integers:
Integers may contain any whole number. They are always represented as signed integers (denoted by the left most bit reserved to indicate if the integer is positive or negative). They are system dependent, so they may have an upper-bound of either 32 bits or 64 bits (2^31-1 or 2^63-1 as signed integers — PHP_INT_MAX is the constant that holds this system-dependent value in PHP). However, PHP is a dynamically typed language so it will automatically convert numbers that exceed these bounds into a more suitable type like floats.

Float or Double:
It may contain any decimal number. They may be either positive or negative.

Strings:
Strings type can contain any number of characters (PHP defines characters in a string as bytes 0×00 through 0xff — in hexadecimal notation — or 0 through 255 — in decimal notation) and has a limitation of roughly 2GB (which is per-string value so that’s normally plenty for most people’s needs). Strings in PHP only support 256 bit character sets (ASCII and Extended ASCII), which sets them apart from some string types in other languages.

Arrays:
An array stores multiple values in one single variable.
For example:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Object:
Object types are  the instances of class definitions. They can store properties, which are made up of property names (similar to array keys) and values (similar to array values).

Resource:
Resource types are normally some link to an external resource that is supplying PHP with data or receiving data from PHP. This link may be to a socket connection, for example, a database connection, a connection to an external or shared library like an image resource, or even a connection to a file handler that’s reading from disk or some stream.

Null:
Null types only have one possible value and that’s null. It is a special type that signifies the absence of value. NULL is also treated as a language constant in PHP and is case-insensitive. PHP considers all undefined variables to be of type NULL.

No comments:

Post a Comment