PHP Data Types

PHP variables can store data of different types including simple string and numeric types to more complex data types like arrays and objects. PHP supports following primitive data types.

  • Integer
  • String
  • Float
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

PHP Integer Data Type

An integer data type is a whole number, without a decimal point, between -2,147,483,648 and 2,147,483,647. Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation. In following examples we will use PHP var_dump() function which returns the data type and value.

Example

<?php
$x = 579;
var_dump($x);
?>

PHP String Data Type

PHP string is sequence of characters, where every character is the same as a byte. A string can hold letters, numbers, and special characters and it can be as large as up to 2GB.

Example

<?php
$str1 = “Hello world!”;
$str2 = ‘Hello world!’;

var_dump($str1);
echo “<br>”;
echo $str2;
?>

PHP Float Data Type

PHP float (also known as double, or real numbers) is a number with a decimal point or a number in exponential form.

Example

<?php
$x = 1.234;
var_dump($x);
?>

PHP Boolean Data Type

A Boolean data type represents only two possible values: TRUE (1) or FALSE (0).

Example

<?php
$x = true;
$y = false;
var_dump($x);
var_dump($y);
?>

PHP Array Data Type

An array data type can store multiple values in single variable. An array is defined as an indexed collection of values where each index is unique and references a corresponding value.

Example

<?php
$colors = array(“Red”,”Grees”,”Blue”);
var_dump($colors);
?>

PHP Object Data Type

An object data type stores data and information on how to process that data. An object is a specific instance of a class which serve as templates for objects. A class is a structure that can contain properties and methods. Objects are created based on this template via the new keyword.

Here’s a simple example of a class definition followed by the object creation.

<?php
class Car {
function Car() {
$this->make = “Honda”;
}
}
// creating class object
$myCar = new Car();

// displaying object properties
echo $myCar->make;
?>

PHP NULL Data Type

The NULL data type is used to represent variables without any data. NULL is the only possible value of type NULL.

Example

<?php
$x = NULL;
var_dump($x);
echo “<br>”;

$x = “Hello World!”;
$x = NULL;
var_dump($x);
?>

PHP Resource Data Type

PHP resource is a special variable which holds a reference to a function or an external resource. The are typically used to opened files and database connections.