What is data type in PHP?

Data type and variable in PHP

Data type defines what type of value a variable can store.

In programming language, a variable is a value that can change.

PHP is a dynamically typed language. In dynamically typed language it is not required to specify the type of a variable because the type will be set at runtime.

To declare a variable in PHP we need to know the following things:

  • The variable begins with the $ symbol followed by a name of the variable.
  • The variable name is case-sensitive ($name and $NAME will be considered two different variables).
  • A variable name does start with a number and only contains alpha-numeric characters(a-z, 0-9) and underscores (_)

Built-in data types in PHP

PHP supports the following built-in data types:

null, bool, int, float, string, array, object, resource

Now we will try to understand different php data types one by one with examples.

null data type

null data type overview

null data type has only one value – null. This is case-insensitive.

Example of using null data type

An example of null is:

<?php
$nullVal = null; // Or, NULL
?>

bool data type

bool data type overview

bool data type only has two values – true or false. This is case-insensitive.

Example of using bool data type

An example of bool is:

<?php
$boolVal = true; // Or TRUE
?>

int data type

int data type overview

An int is a number which may be positive or negative and should not have a decimal point(i.e. should be a whole number).

Example of using int data type

Example of int is:

<?php
$intVal = 2;
$intVal = -2;
?>

float data type

float data type overview

A float is a number and should have a decimal point (must be a fractional number).

Example of using float data type

An example of float is:

<?php
$floatVal = 2.2;
?>

string data type

string data type overview

string is a collection of characters (character is equivalent to a byte).

Example of using string data type

An example of string is:

<?php
$stringVal = 'blue';
?>

array data type

array data type overview

An array stores a number of values in one single variable.

Example of using array data type

An example of an array is:

<?php
$arrayVal = ['blue', 'green', 'red'];
?>

object data type

object data type overview

An object is an instance of a class. A class is a collection of its constants, variables or properties, and functions or methods. To create an object new keyword is used.

Example of using object data type

The easiest way to instantiate an empty object is:

<?php
$emptyObject = new stdClass();
?>

resource data type

resource data type overview

A resource holds references to external resources. Special functions are used to create and use resources.

Example of using resource data type

A database call is a common example of using the resource data type.