Categories
PHP

Data Types

Variables don’t need to be declared, and they have no type until they are assigned a value. PHP is loosely typed, meaning that it automatically determines the data type at the time data is assigned to each variable. It means a variable can hold an integer and then later in the script it can hold a string or some other data type.

This tutorial covers the following topics:

The following code fragment shows a variable $var assigned the value of an expression, the Integer 15. Therefore, $var is defined as being of type integer:

$var = 15;

Because the variable in this example is used by assigning a value to it, it’s implicitly declared. Variables in PHP are simple: when they are used, the type is implicitly defined-or redefined-and the variable is implicitly declared. The variable type can change over the lifetime of the variable. Consider an example:

//Example
$var = 15;
$var = "Cat";

This fragment is acceptable in PHP. The type of $var changes from integer to string as the variable is reassigned. Letting PHP change the type of a variable as the context changes is very flexible and a little dangerous.

For example, suppose that you have created code to manipulate an array variable. If the variable in question instead contains a number value and no array structure is in place, errors will occur when the code attempts to perform array-specific operations on the variable.

Different types of data take up different amounts of memory and may be treated differently when they are manipulated by a PHP script. It is important to have an understanding of the data types that PHP works with:

Data TypeCategoryDescription
stringScalartext (a collection of characters)
booleanScalartrue or false
floatScalara floating-point number
integerScalara whole number
arrayCompositean ordered set of keys and values
objectCompositean instance of a class
resourceSpecialreference to an external resource (e.g. a database link.)
nullSpecialrepresents a variable with no value
mixedSpecialany type
callableSpeciala function
PHP Data Types

Scalar Types

Variables of a scalar type can contain a single value at any given time. Scalar values can’t break into smaller pieces.

String

You’ve already seen examples of strings earlier, when echo( ) and print( ) were introduced, and string literals are covered further in the next sections. Consider two example string variables:

$variable = "This is a string";
$test = 'This is also a string';

PHP can create double and single-quoted string literals. If double quotation marks are needed as part of a string, the easiest approach is to switch to the single-quotation style:

echo 'This works';
echo "just like this.";
// And here are some strings that contain quotes
echo "This string has a ': a single quote!";
echo 'This string has a ": a double quote!';

Boolean

Boolean variables are as simple as they get: they can be assigned either true or false. Here are two example assignments of a Boolean variable:

$variable = false;
$test = true;

Integer

An integer is a whole number specified in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation.

Hexadecimal numbers are preceded with a 0x, octal with a 0, and binary numbers with a 0b. Consider the following examples:

$var1 = 123;
// decimal number

$var2 = 0b1111011;
// binary number (123 in decimal)

$var3 = 0173;
// octal number (123 in decimal)

$var4 = 0x7B;
// hexadecimal number (123 in decimal)

Float (or double)

A float can also be represented using an exponential notation:

// This is a float that equals 1120
$var1 = 1.12e3;

// This is also a float that equals 0.02
$var2 = 2e-2;

//A decimal float
$var3 = 1.55;

Compound or Composite Types

Variables of a compound type are made up of multiple scalar values or other compound values.

Arrays

An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

$array = array(
         'one'   => 'Apple',
         'two'   => 'Mango',
         'three' => 'Banana'
        );

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

$array = [
         'one'   => 'Apple',
         'two'   => 'Mango',
         'three' => 'Banana'
        ];

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key:

$array = [
         'Apple',
         'Mango',
         'Banana'
        ];
        
// OR
$array2 = array(
         'Apple',
         'Mango',
         'Banana'
        );

We’ll discuss the Arrays in more detail later in Arrays section.

Objects

An object is an instance of a class. To create a new object, we usually use the new statement to instantiate a class.

$anObject = new stdClass();

stdClass is PHP’s generic empty class. It is useful for anonymous objects, dynamic properties, etc. we’ll discuss the Classes later in the Classes section.

Special Types

Resource

A resource is a special variable, holding a reference to an external resource. For example, open, read, or create a file, connection or link to databases, FTP streams, file or directory handle, etc.

Each resource can be accessed, modified, or closed by its own special functions. For example, to open and close a directory resource we use:

$dir = opendir('/path/to/dir');
//$dir handle holds the external resource

closedir($dir);
//freed the resource

Null

The null is used to represent a variable with no value. Such a variable is considered to be of the special null data type.

$var = null; // variable is set to null

In PHP, it is possible to use variables that have not been assigned a value. Such undefined variables are then automatically created with the null value.

echo $undefinedVar; // variable is set to null

Note:
PHP issues an error notice when undefined variables are used. Depending on the PHP error reporting settings, this message may or may not be displayed.

Callbacks / Callables

Some functions like usort() or array_map() accept user-defined callback functions as a parameter. Callback functions can be:

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except: array()echoempty()eval()exit()isset()list()print or unset().

Callback function example:

function callBack($p){
 return $p * 2;
}

function func($arr, $cb){
 foreach ($arr as $v){
  echo $cb($v)." ";
 }
}
$a = [1,2,5];
func($a, 'callBack');
//2 4 10

Callback example using a Closure:

function func($arr, $cb){
 foreach ($arr as $v){
  echo $cb($v)." ";
 }
}

$a = [1,2,5];
func($a, function ($p){
 return $p * 2;
});
//2 4 10

Iterables

Iterable, introduced in PHP 7.1, accepts any array or object implementing the Traversable interface (to detect if a class is traversable using foreach). Both of these types are iterable using foreach and can be used with yield from within a generator.

Iterable can be used as a parameter type to indicate that a function requires a set of values. If a value is not an array or instance of Traversable, a TypeError will be thrown:

<?php
function itrableFunc(iterable $iterable) {
 foreach ($iterable as $value) {
  echo $value.' ';
 } 
}

$arr = ['a','b','c'];
itrableFunc($arr);
//a b c

$str = 'hello';
itrableFunc($str);
//Fatal error: Uncaught TypeError...

Data type examples

//Integer
$intg  = 1;
$intg2 = -2;

//Float
$flt  = 1.0;
$flt2 = -2.1;

//Boolean
$bol  = true;
$BOL  = TRUE;
$bol2 = false;
$bol3 = FALSE;

//String
$str  = 'A string';
$str2 = "Another string";
$str3 = '1';
$str4 = '2.0';
$str5 = "-2";
$str6 = 'true';
$str7 = "false";

//Null
$varNull = null;
$VARnull = NULL;

truefalse and null are case-insensitive constants, don’t enclose them in quotes.


Data types in PHP:

  1. Data Types
  2. Determine Variable Data Type
  3. Type Conversion: Convert variable data type
  4. Type Declaration
  5. Strict Typing Mode
  6. Testing, setting, and unsetting variables