×
Author:
Website:
Page title:
URL:
Published:
Last revised:
Accessed:

Variables and Datatypes

Overview

In any programming or scripting language, a variable is a named location in memory that holds the value of a number, character, text string, or complex data type. In PHP, all variables are prefixed by a dollar sign ($). A variable is created as soon as you declare it and assign a value to it. The basic syntax for declaring a variable in PHP is shown below (note that variable names are case-sensitive).

$varName = value;

PHP is said to be a loosely (or dynamically) typed language, because the data type of a variable does not have to be specified before a value is assigned to it. A value can be assigned to a variable when it is created, and PHP automatically selects the correct datatype for the variable according to the value assigned. The amount of memory allocated to a variable, together with the kind of operations that can be carried out on it, will depend on the datatype selected.

Not only can the value assigned to the variable be changed, but the type of value assigned to the variable can be changed, as we shall see. We can also assign the same value to multiple variables. For example:

$tankATemp = $tankBTemp = $tankCTemp = 0;

The naming rules for PHP variables are simple. A variable name must start with either a letter or an underscore character ("_"), and may only contain alpha-numeric characters (a-z, A-Z, and 0-9) and the underscore character. Variable names should not contain spaces, and if a variable name consists of two (or more) words, they should either be separated by an underscore, or the first letter in each new word should be an uppercase character, as shown below.

$someVariable;
$anotherVariable;

PHP variables can store data of different types. The datatypes supported by PHP are categorised as scalar datatypes, compound datatypes, and special datatypes. Scalar datatypes are used for simple variables that will hold a single value. The following are all scalar datatypes:

  • String - a string of text consisting of one or more
  • Integer - an integer value in the range -263 to 263-1
  • Float - a double-precision floating point number
  • Boolean - a value that can represent either TRUE or FALSE

Compound datatypes are datatypes that can hold collections of variables, either of the same type or different types. Two compound datatypes are supported by PHP:

  • Array - a named and numerically indexed or keyed collection of variables
  • Object - an instance of a programmer-defined class

PHP also has two special data types:

  • NULL - represents a variable to which no value has been assigned
  • Resource - represents some external resource, such as a database connection

Strings

A string variable is a variable that contains a sequence of zero or more alpha-numeric characters or other printable characters within quotes. The quotes can be single or double, but not both (for example "Hello World!" or 'Hello World!' but not "Hello World!' or 'Hello World!". String variables are mainly used to store and manipulate text, and the default character encoding is UTF-8. We can declare and use a string variable (in the ubiquitous "Hello World!" program) as follows:

<?php
$x = "Hello World!";
echo $x; // Hello World!
?>

One difference to note between strings that are enclosed within double quotes and those enclosed between single quotes is that strings declared inside double quotes allow variable parsing, whereas strings declared within single quotes don't. For example:

<?php
$str = "Hello World!";
echo "$str"; // Hello World!
?>

<?php
$str = "Hello World!";
echo '$str'; // $str
?>

Be aware also that in order for escape sequences to be correctly interpreted, you must use double quotes rather than single quotes to enclose a string. Escape sequences in singly-quoted strings will be interpreted literally. For example:

<?php
echo "Price: \$10.99"; // Price: $10.99
?>

<?php
echo 'Price: \$10.99'; // Price: \$10.99
?>

One thing to be aware of is that that some of the commonly used escape sequences with which you may be familiar, such as the newline, carriage return and tab escape sequences, will have no effect on the text displayed in a browser. For example:

<?php
echo "This is a line of text.\nThis is another line of text.";
// This is a line of text. This is another line of text.
?>

As you can see, the two sentences are both displayed on the same line - the newline escape character (\n) is not recognised by HTML (although it has inserted a space between the two statements). If you look at the source HTML code for the document sent to the browser, however, it is a different story:


A newline is inserted in the HTML code

A newline is inserted in the HTML code


PHP provides numerous functions for working with text strings, some of which we will be exploring when we discuss working with strings in PHP elsewhere in this section.

Note that there are no limits on the length of a string in PHP other than the practical limits imposed by the amount of memory available on a particular system. We would however recommend not assigning a chunk of text the size of Leo Tolstoy's War and Peace to a single text variable for performance reasons! 

Integers

The integer datatype can represent whole numbers in the range -2,147,483,648 to 2,147,483,647 (-231 to 231-1) on 32-bit systems or -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (-263 to 263-1) on 64-bit systems. As well as representation in decimal (base 10) form, integers can also be represented as hexadecimal (base 16), octal (base 8) or binary (base 2) numbers. The decimal representation of an integer value can be converted to its hexadecimal, octal, or binary representation using special built-in PHP functions. For example:

<?php
$num = 123;
echo "\$num as a decimal number = " . $num . "<br>";
// $num as a decimal number = 123
echo "\$num as a hexadecimal number = " . dechex($num) . "<br>";
// $num as a hexadecimal number = 7b
echo "\$num as an octal number = " . decoct($num) . "<br>";
// $num as an octal number = 173
echo "\$num as a binary number = " . decbin($num) . "<br>";
// $num as a binary number = 1111011
?>

Note that, although the conversion functions produce the correct values in each case, they do not display a prefix to indicate what their number base is, although hexadecimal and binary values are fairly easy to spot, because numbers in hexadecimal format often contain characters in the range [a-f] or [A-F], and binary numbers only ever contain ones and zeros. Octal numbers, of course, only contain digits in the range [0-7].

We need to know the correct format to use, however, when declaring variables using hexadecimal, octal or binary values. For example:

<?php
$hex = 0x7b;
$oct = 0o173;
$bin = 0b1111011;
echo "The value of \$hex is 0x" . dechex($hex) . " (" . $hex . ")<br>";
// The value of $hex is 0x7b (123)
echo "The value of \$oct is 0o" . decoct($oct) . " (" . $oct . ")<br>";
// The value of $oct is 0o173 (123)
echo "The value of \$bin is 0b" . decbin($bin) . " (" . $bin . ")<br>";
// The value of $bin is 0b1111011 (123)
?>

As we can see here, in order to declare a numeric variable using hexadecimal notation, we precede the hexadecimal number with the characters "0x". For octal, we use "0o" as the prefix, and for binary we use "0b". In all cases, negative integer values are preceded by the minus sign (-), for example -0x7b, -0o173, or -0b1111011, all of which are equal to the decimal value -123.

We stated earlier that integer variables could take values in the range -2,147,483,648 to 2,147,483,647 (-231 to 231-1) on 32-bit systems, or -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (-263 to 263-1) on 64-bit systems. This is probably true for the majority of computer systems you will encounter, but in order to be sure you can use the PHP_INT_SIZE constant to find the sizes (in bytes) of a stored integer value on a specific platform. For example:

<?php
echo "The size of an integer on this platform is ";
echo PHP_INT_SIZE . " bytes.";
// The size of an integer on this platform is: 8 bytes.
?>

This tells us that the size of a stored integer is 8 bytes, or 64 bits. In similar fashion, we can confirm the maximum and minimum values that an integer value can take on the current system using the PHP_INT_MAX and PHP_INT_MIN constants:

<?php
echo "The maximum permitted value of an integer<br>value on this platform is ";
echo PHP_INT_MAX;
echo "<br>and the minimum permitted size is ";
echo PHP_INT_MIN . ".";
// The maximum permitted value of an integer
// value on this platform is 9223372036854775807
// and the minimum permitted size is -9223372036854775808.
?>

If the maximum or minimum values for an integer are exceeded, PHP will convert the number to a float automatically.

Floating-point numbers

A floating-point number in PHP is a signed double precision floating point number (i.e. a positive or negative number that has both an integer component and a fractional component, separated by a period). A floating-point variable is actually stored as two numbers. The mantissa (or significand) is the sequence of significant digits that make up the number itself, and the exponent determines the magnitude of the number - in other words, it tells us where the decimal point goes.

PHP represents floating-point numbers according to the IEEE Standard for Floating-Point Arithmetic (IEEE 754), the current version of which (IEEE 754-2019) was published in July 2019. A float variable occupies 64 bits of memory, and can store values of up to 1.7976931348623E+308 (that's a very large number!). Out of those 64 bits, 1 bit is used to represent the sign, 52 bits are used for the mantissa, and 11 bits are used for the exponent.

Bear in mind, however, that the maximum precision of a floating-point number is 15 digits. What this means in practice is that, regardless of how big or how small the number is, only numbers with 15 digits or less, regardless of where those digits appear in relation to the decimal point, can be represented precisely with no loss of precision. A general rule of thumb for floating-point numbers is that the larger the number is, the less precision we can expect to achieve.

As with the integer datatype, PHP provides several constants related to floating-point numbers. The constants most likely to be of immediate interest to us are PHP_FLOAT_MAX, which returns the largest floating-point number that can be represented, and PHP_FLOAT_MIN, which returns the smallest positive floating-point number that can be represented. For example:

<?php
echo "The maximum size of a float is ";
echo PHP_FLOAT_MAX . ".<br>";
// The maximum size of a float is 1.7976931348623E+308.
echo "The minimum size of a float is ";
echo PHP_FLOAT_MIN;
// The minimum size of a float is 2.2250738585072E-308
?>

The value of a floating-point variable can be specified using either its full decimal form or scientific notation. For the full decimal form, the decimal point (.) separates the integer (whole number) and the fractional parts of the number, with the digits to the left of the decimal point representing the integer part and the digits to the right of the decimal point representing the fractional part.

Using scientific notation, the number is written as the product of a number between 1 and 10 (the coefficient) and some integer power of 10 (the exponent). The exponent is prefixed with the letter "e" or "E", and appears immediately to the right of the coefficient.

The following code demonstrates two ways in which we can specify the same floating-point number:

<?php
$float1 = 234.567;
$float2 = 2.34567E2;
echo $float1 . "<br>"; // 234.567
echo $float2; // 234.567
?>

As indicated above, the exponent of a floating-point number in PHP is an unsigned 11-bit integer with a value of between 1 and 2046 (the values 0 and 2047 each have special meanings) to which a negative offset of 1023 is applied to allow exponent values of between -1022 and 1023.

Bear in mind, however, that numbers exceeding the value of PHP_FLOAT_MAX cannot be represented as 64-bit double-precision numbers, and will automatically evaluate to INF (infinity). Similarly, numbers significantly smaller than PHP_FLOAT_MIN will essentially be too small to be meaningful, and will evaluate to zero.

The float datatype allows us to store a huge range of values, but there is an obvious trade-off in terms of magnitude versus precision. When carrying out calculations involving floating-point variables, therefore, keep in mind that the results may be subject to some loss of precision. Comparing floating-point values that are the result of such calculations is also potentially error-prone for the same reason.

One final thing to note in relation to floating-point variables is that, by default, the number of digits displayed after the decimal point will be limited to the number of digits required to express the value accurately. For example:

<?php
$val_1 = 2.175005;
$val_2 = 2.104995;
echo "The product of \$val_1 and \$val_2 is: " . $val_1 * $val_2 . "<br>";
// The product of $val_1 and $val_2 is: 4.578374649975
echo "The sum of \$val_1 and \$val_2 is: " . $val_1 + $val_2;
// The sum of $val_1 and $val_2 is: 4.28
?>

If we want to display the result of a calculation using a specific number of digits after the decimal point, we will have to apply the appropriate formatting. We will be discussing this topic, together with the question of how to handle problems arising from the potential loss of precision in floating-point calculations, in more detail elsewhere in this section.

Boolean values

A Boolean variable can represent two possible states: TRUE or FALSE. Boolean values are used in computer programming to determine whether a statement is true or false. For example:

<?php
$bool = (2 + 2) == 4;
echo "The variable \$bool has the type: ";
var_dump($bool);
// The variable $bool has the type: bool(true)
?>

PHP recognises that the value of the statement "(2 + 2) == 4" can only be either true or false, because we are using the equality operator to assert that the left- and right-hand operands are equal. It therefore assigns the type bool (Boolean) to the variable $bool, which in this case evaluates to TRUE.

Be careful when using Boolean logic to compare numeric values though, especially when dealing with non-integer values. Consider the following example:

<?php
$pi = 3.14159;
var_dump($pi == M_PI); // bool(false)
echo "<br>The value of \$pi is " . $pi . "<br>";
// The value of $pi is 3.14159
echo "The value of M_PI is " . M_PI;
// The value of M_PI is 3.1415926535898
?>

We have declared a variable $pi to represent the mathematical constant pi, and have assigned it a value of 3.14159, which is accurate to five decimal places - adequate for most purposes. We have then tested $pi for equality with the constant M_PI, which is a built in PHP constant representing pi. As you can see, the value of $pi (3.14159) does not equal the value represented by M_PI (3.1415926535898), so the expression $pi == M_PI evaluates to FALSE.

Boolean values are also used to determine whether the condition(s) specified for a conditional statement have been satisfied, or whether the exit condition for a loop has been met. For example:

<?php
for ($i = 0; $i <= 5; $i++)
{
echo "<br> \$i = " . $i . " ";
var_dump($i == 5);
}
echo "<br>Exiting loop.";
// $i = 0 bool(false)
// $i = 1 bool(false)
// $i = 2 bool(false)
// $i = 3 bool(false)
// $i = 4 bool(false)
// $i = 5 bool(true)
// Exiting loop.
?>

Note that the integer values 1 and 0 represent TRUE and FALSE respectively, but other values can be interpreted as either TRUE or FALSE in the context of evaluating the truth or falsehood of an expression. The following rules are used to interpret whether a value is evaluated as TRUE or FALSE:

  • A value of zero (0) evaluates to FALSE. All other non-zero integer or floating-point values are interpreted as TRUE (note that it is not recommended to use floating point values to represent Boolean values).
  • An empty string ("") evaluates to FALSE. All other (non-empty) string values are interpreted as TRUE.
  • A value of NULL always evaluates to FALSE.
  • An empty array variable evaluates to FALSE. Non-empty arrays evaluate to TRUE.
  • An object, none of whose member variables have been assigned a value, evaluates to FALSE. Otherwise, the object evaluates to TRUE.

Arrays

An array stores multiple values in a single variable. Usually, the values stored in an array are of the same type, or are closely related in some way, or both. For example, we might have an array that stores a list of names, the months of the year, or the days of the week. Here is how we might create and access an array that stores the days of the week:

<?php
$weekDays = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
echo "The first day of the week is: " . $weekDays[0];
// The first day of the week is: Monday
?>

In the above example, we have used the array() function to create an indexed array by passing the array elements to the function as a comma delimited list of array elements - in this case, the names of the days of the week. In order to access an array element, we use the name of the array variable followed by the numerical index of the value we want to address enclosed between square brackets (note that PHP array elements are indexed starting from 0).

We could create exactly the same array variable using a slightly more concise notation that avoids use of the array() function as follows:

<?php
$weekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
echo "The first day of the week is: " . $weekDays[0];
// The first day of the week is: Monday
?>

As you can see, this method differs from the first in that we assign the list of array elements, enclosed between square brackets, directly to the array variable. The resulting array is identical to that produced in the previous example. The two methods can be used interchangeably, and the choice of which method to use appears to be largely a matter of personal preference, although the second method is generally preferred as it is considered to be more readable.

The kind of array we created in the previous two examples is an indexed array because each element can be accessed using a numerical index. There is another kind of array, called an associative array, that stores array elements as key-value pairs. Here is an example:

<?php
$colors = array(
"Black"=>"#000000",
"Red"=>"#ff0000",
"Green"=>"#00ff00",
"Blue"=>"#0000ff",
"White"=>"#ffffff",
);
echo "The colour hex codes are: <br>";
// The colour hex codes are:
echo $colors["Black"] . " (Black)<br>";
// #000000 (Black)
echo $colors["Red"] . " (Red)<br>";
// #ff0000 (Red)
echo $colors["Green"] . " (Green)<br>";
// #00ff00 (Green)
echo $colors["Blue"] . " (Blue)<br>";
// #0000ff (Blue)
echo $colors["White"] . " (White)<br>";
// #ffffff (White)
?>

As you can see, each array element in the $colors array consists of a key (in this case, the name of a colour) followed by the value assigned to the element (a string representing the colour's hexadecimal RGB code). As with the indexed array example, we can create the same associative array without using the array() function by using the more concise square brackets notation:

<?php
$colors = [
"Black"=>"#000000",
"Red"=>"#ff0000",
"Green"=>"#00ff00",
"Blue"=>"#0000ff",
"White"=>"#ffffff",
];
.
.
.
?>

Accessing an element in an associative array is achieved in similar fashion to accessing an element in an indexed array, except that instead of a numerical index inside the square brackets, the key associated with the element is used. One advantage of this is that it is not necessary to know the position of the element within the array in order to access it, and the array elements do not need to be assigned in any particular order.

It is also possible to create multidimensional arrays in which each array element is itself an array. The elements of this nested array can themselves be arrays, and so on. The degree of nesting possible is not constrained to a particular number of levels, but in practical terms anything beyond three levels of nesting (i.e. a three-dimensional array) would be considered somewhat difficult to manage. The following example creates a two-dimensional array:

<?php
$groupA = [
[
"team" => "Germany",
"won" => 2,
"drawn" => 1,
"lost" => 0,
],
[
"team" => "Switzerland",
"won" => 1,
"drawn" => 2,
"lost" => 0,
],
[
"team" => "Hungary",
"won" => 1,
"drawn" => 0,
"lost" => 2,
],
[
"team" => "Scotland",
"won" => 0,
"drawn" => 1,
"lost" => 2,
]
];

echo "Germany's performance in Euro 2024 group stage:<br><br>";
echo "Won: " . $groupA[0]["won"] . "<br>";
echo "Drawn: " . $groupA[0]["drawn"] . "<br>";
echo "Lost: " . $groupA[0]["lost"] . "<br>";
$points = ($groupA[0]["won"]) * 3;
$points += ($groupA[0]["drawn"]);
echo "Points: " . $points;

// Germany's performance in Euro 2024 group stage:
//
// Won: 2
// Drawn: 1
// Lost: 0
// Points: 7
?>

In this example a top-level indexed array has four elements, each of which is a four-element associative array. Values in a two-dimensional array are accessed using multiple indices - in this case, a numerical index followed by an array key. Note that we have used the values stored in the second-level array to calculate the value of $points rather than creating an additional key-value pair.

We will be revisiting arrays elsewhere in this section, where we will describe the kind of situations in which they might be used, the kind of operations that can be performed on them, and some of the functions provided by PHP for performing those operations.

Objects

Objects are a central tenet of object-oriented programming - which is blindingly obvious when you think about it, but we've said it anyway! An object is a collection of properties - the values associated with an object that describe its state, and methods - the functions provided by the object to access and manipulate its properties. A property can be any kind of variable, including another object.

An object is created from a template - basically a kind of blueprint for the object - called a class. A class is not an object in its own right - it represents a particular type of object. An object is an instance of a class. It inherits all of the properties and methods defined by the class, but the properties will have a distinct set of values that are unique to that object. An example should help to clarify this relationship:

<?php
class car {
public $make;
public $model;
public $color;
public function __construct($make, $model, $color) {
$this->make = $make;
$this->model = $model;
$this->color = $color;
}
public function report() {
return "This car is a " . $this->color . " " . $this->make . " " . $this->model . ".";
}
}

$myCar = new car("Fiat", "Punto", "White");
echo $myCar->report();
// This car is a White Fiat Punto.
?>

In this code example, we have created a class called car which has three member variables (the properties) called $make, $model and $color. It also has one method, report(), whose purpose is to return a message informing the user of the colour, make and model of the car defined by the object.

Each time a new object of type car is created using the new keyword, the class constructor __construct() is called, and will create a new object of type car using the arguments passed to it. The constructor expects three arguments - the make, model and colour of the car.

We could of course add additional properties and methods to the car class to reflect the kind of data we might want store about a car, and the ways in which we might want to use that data. The above example serves purely to demonstrate how objects are created and accessed. We will return to the subject of classes and objects in far greater detail elsewhere in this section.

The NULL value

NULL (or null - it's not case-sensitive) is a special PHP datatype that represents a variable to which a value of NULL has been assigned. For example:

<?php
$name = NULL;
echo "The value of 'name' is: ";
var_dump($name); // The value of 'name' is: NULL
?>

If a variable is created without assigning a value to it, attempting to use the variable before it has been initialised results in a warning being generated even though the var_dump() function, when applied to the variable, returns NULL. The variable does not actually have a value - it is undefined. For example:

<?php
$name;
echo "The value of name is: "; // The value of name is:
var_dump($name); // Warning: Undefined variable $name . . .
// NULL
?>

The thing to take on board here is that you should always initialise a variable when you declare it. If you do not want to give it a specific value immediately, you should assign it a value of NULL to avoid inadvertently generating a warning. Note that you can also clear a variable's existing value, if necessary, by assigning it the value NULL. For example:

<?php
$myName = "Fred";
echo "My name is " . $myName . "<br>"; // My name is Fred
$myName = NULL;
echo "My name is " . $myName; // My name is
?>

A NULL value always evaluates to false when tested with the IsSet() function:

<?php
$name = NULL;
if(IsSet($name)){
echo "The value of \$name is set.";
}
else {
echo "The value of \$name is not set.";
// The value of $name is not set.
}
?>

A NULL value also evaluates to FALSE when used in a Boolean context:

<?php
$name = NULL;
if ($name) {
echo "Name exists!";
}
else {
echo "Name has no value."; // Name has no value.
}
?>

A NULL value may also evaluate to the empty string, or zero, depending on context:

<?php
$name = $num = NULL;
if($name == ""){
echo "The value of \$name is the empty string.<br>";
} // The value of $name is the empty string.
echo "The value of \$num + 5 is " . $num + 5;
// The value of $num + 5 is 5
?>

In order to check whether the value of a variable is NULL, you can either use the is_null() function or the equality operator (===):

<?php
$name = $address = NULL;
if($name === NULL){
echo "The value of \$name is NULL.<br>";
} // The value of $name is NULL.
if(is_null($address)){
echo "The value of \$address is NULL.";
} // The value of $address is NULL.
?>

Resources

The PHP resource type stores a reference to an external resource such as a file, a database connection or a network connection, that can be managed by PHP. Let's demonstrate how this works. We'll go through the process of creating a text file called "notes.txt":

<?php
$fileName = "notes.txt";
if (file_exists($fileName)) {
$myFile = fopen("notes.txt", "r");
echo "The 'notes.txt' file is open.<br>";
echo "\$myFile has the type: " . gettype($myFile);
}
else {
echo "The 'notes.txt' file does not exist. Creating . . .<br>";
$myFile = fopen("notes.txt", "w") or die("Unable to create file.");
echo "The 'notes.txt' file has been created successfully.<br>";
echo "\$myFile has the type: " . gettype($myFile);
}
?>

If the file "notes.txt" does not exist, this code will create it. If nothing goes wrong, we will see the following messages:

The 'notes.txt' file does not exist. Creating . . .
The 'notes.txt' file has been created successfully.
$myFile has the type: resource

If we run the script again, and assuming that the file was created successfully, we will see:

The 'notes.txt' file is open.
$myFile has the type: resource

The fopen() function used to open a file for reading or writing returns a file handle that has the datatype resource in PHP. Similarly, when we open a connection with a mySQL database, the connection returned by the mysqli() function is also a variable of type resource. That's all we really need to know about resource variables for the moment. We will be revisiting the subject in greater detail elsewhere in this section.

Getting the datatype

There are several ways in which we can determine a variable's datatype. One method is to use the gettype() function. For example:

<?php
$str = "Hello world!";
$int = 2;
$flt = 2.0;
$boo = TRUE;
$arr = [1,3,5,7,11,13];
class myClass {
// properties and methods
}
$obj = new myClass();

echo "Here is a list of variables and their datatypes:<br>";
// Here is a list of variables and their datatypes:
echo "\$str = " . gettype($str) . "<br>"; // $str = string
echo "\$int = " . gettype($int) . "<br>"; // $int = integer
echo "\$flt = " . gettype($flt) . "<br>"; // $flt = double
echo "\$boo = " . gettype($boo) . "<br>"; // $boo = boolean
echo "\$arr = " . gettype($arr) . "<br>"; // $arr = array
echo "\$obj = " . gettype($obj); // $obj = object
?>

You can also get both the data type and the value of any variable using the var_dump() function. For example:

<?php
$str = "Hello world!";
$int = 2;
$flt = 2.0;
$boo = TRUE;
$arr = [1,3,5];
class myClass {
// properties and methods
}
$obj = new myClass();

echo "Here is a list of variables with datatypes and values:<br>";
// Here is a list of variables with datatypes and values:
cho "\$str = ";
var_dump($str);
// $str = string(12) "Hello world!"
echo "<br>\$int = ";
var_dump($int);
// $int = int(2)
echo "<br>\$flt = ";
var_dump($flt);
// $flt = float(2)
echo "<br>\$boo = ";
var_dump($boo);
// $boo = bool(true)
echo "<br>\$arr = ";
var_dump($arr);
// $arr = array(3) { [0]=> int(1) [1]=> int(3) [2]=> int(5) }
echo "<br>\$obj = ";
var_dump($obj);
// $obj = object(myClass)#1 (0) { }
?>

PHP also provides a number of functions that can be used to check whether a variable is of a particular datatype. For example:

is_string() - checks to see if a variable is a string
is_int() - checks to see if a variable is an integer
is_float() - checks to see if a variable is a float
is_bool() - checks to see if a variable is a boolean
is_array() - checks to see if a variable is an array
is_object() - checks to see if a variable is an object
is_null() - checks to see if a variable is NULL

Each of these functions takes the name of a variable as its argument, and returns either TRUE or FALSE, depending on whether or not the variable is of the datatype being checked for or not.

Type conversion

As we have stated, PHP is a dynamically typed language. The datatype of a variable is determined automatically as soon as we assign a value to it. A variable that is assigned an integer value will be an integer, and a variable that is assigned a string value will be a string. However, it is perfectly possible to assign a value of any datatype to an existing variable, regardless of the datatype it currently has. For example:

<?php
$myVar = 12;
echo "\$myVar has value '" . $myVar . "'";
echo " and datatype '" . gettype($myVar ) . "'<br>";
// $myVar has value '12' and datatype 'integer'
$myVar = "Hello World!";
echo "\$myVar has value '" . $myVar . "'";
echo " and datatype '" . gettype($myVar ) . "'";
// $myVar has value 'Hello World!' and datatype 'string'
?>

You can also change the datatype of an existing variable explicitly without assigning it a new value using casting. For example:

<?php
$myVar = 123;
echo "\$myVar has value '" . $myVar . "'";
echo " and datatype '" . gettype($myVar ) . "'<br>";
// $myVar has value '123' and datatype 'integer'
$myVar = (string) $myVar ;
echo "\$myVar has value '" . $myVar . "'";
echo " and datatype '" . gettype($myVar ) . "'<br>";
// $myVar has value '123' and datatype 'string'
$newVar = $myVar . " Go!";
echo $newVar;
// 123 Go!
?>

In the above example we converted an integer to its string representation in order to be able to concatenate the resulting value ("123") with another string value, in order to create a new string variable ($newVar) with a value of "123 Go!".

We can also convert a string representing a numeric value to the actual numeric value it represents, either as an integer value or as a floating-point value. For example:

<?php
$myVar = "123.5";
echo "\$myVar has value '" . $myVar . "'";
echo " and datatype '" . gettype($myVar ) . "'<br>";
// $myVar has value '123.5' and datatype 'string'
$myVar = (float) $myVar ;
echo "\$myVar has value '" . $myVar . "'";
echo " and datatype '" . gettype($myVar ) . "'<br>";
// $myVar has value '123.5' and datatype 'double'
$newVar = $myVar * 4;
echo "\$newVar has value '" . $newVar . "'";
echo " and datatype '" . gettype($newVar) . "'<br>";
// $newVar has value '494' and datatype 'double'
?>

Note that the gettype() function declares the type of the variable (after the conversion) as "double" even though we explicitly cast it to type "float". In fact (according to the official PHP documentation) the term "double" is an alias for "float". We could, for example, have used the following line of code with identical results:

$myVar = (double) $myVar;

Note, however that "real" was also an alias for float at one time, but has now been deprecated. Bearing that in mind, we suggest always using "float" to ensure that a future decision to deprecate "double" - however unlikely that may be - will not break our code.

We mentioned above that assigning a value of a different type to an existing variable will change the variable's type automatically, depending on the new value assigned. The type of a variable used in certain types of operation can also be changed dynamically if the need arises. Consider the following example:

<?php
$pi = "3.14159";
$radius = 2.5;
echo "A circle has a radius of " . $radius . " metres.<br>";
// A circle has a radius of 2.5 metres.
echo "Its circumference is " . 2 * $pi * $radius . " metres.<br>";
// Its circumference is 15.70795 metres.
echo "The variable \$pi still has the datatype '";
echo gettype($pi) . "'.";
// The variable $pi still has the datatype 'string'.
?>

In the above example we have not explicitly changed the value of the variable $pi to its floating-point equivalent through type casting. Nor have we assigned the floating-point value 3.14159 to it.

As it turns out, we needn't bother doing either of these things because PHP has worked out that we are multiplying the value of $pi by an integer value, so it dynamically converts the value used to a floating-point number to facilitate the multiplication operation. Note, however, that in this case the datatype of the variable $pi itself is unchanged - it is still a string variable.

We should however be careful, when using mixed datatypes in calculations, not to rely too heavily on PHP to always correctly interpret what we require in the way of an outcome. We may have escaped the possible adverse effects of storing the value of PI as a string in the above example, but relying on PHP to always correctly interpret our intentions when there is a less ambiguous alternative is poor practice, often inefficient from a performance point of view, and can lead to unexpected results.

Another pitfall to note is that changing the datatype of a variable will also change the actual value stored in the variable. This is often not a problem. We can happily convert back and forth between integers and strings, or between floating-point numbers and strings (depending on the precision of the floating-point number) without losing or altering the meaning of the information stored.

There are a few situations, however, where the conversion process is not reversible, and will significantly change the meaning of the stored value. One obvious example is converting a non-numeric string variable to a number. For example:

<?php
$str = "Hello world";
$str = (integer) $str;
echo "The value of \$str is " . $str;
// The value of $str is 0
?>

Another, maybe not quite so obvious example, is where we carry out conversions between integer and floating-point datatypes. Converting an integer to a floating-point value (and back again) works fine. For example:

<?php
$num = 12;
echo "The value of \$num is " . $num . "<br>";
// The value of $num is 12
$num = (float) $num;
echo "The value of \$num is " . $num . "<br>";
// The value of $num is 12
$num = (integer) $num;
echo "The value of \$num is " . $num;
// The value of $num is 12
?>

Converting a floating-point value to an integer and back again does not work quite so well. For example:

<?php
$pi = 3.14159;
echo "The value of \$pi is " . $pi . "<br>";
// The value of $pi is 3.14159
$pi = (integer) $pi;
echo "The value of \$pi is " . $pi . "<br>";
// The value of $pi is 3
$pi = (float) $pi;
echo "The value of \$pi is " . $pi;
// The value of $pi is 3
?>

As you can see, converting a floating-point variable to an integer variable can result in a loss of precision. Sometimes that may be what we want to achieve, although there are usually better ways to achieve this kind of change. The main lesson to be learned here is that, while type conversion, both explicit and implicit, can be a powerful tool, it is one that should be used with caution.

Comparing variables

We may want to compare the value of variables for a number of reasons. String comparison, for example, is useful if we are trying to arrange an array of text-based data into alphabetical order. Numerical comparison can be used to see whether two or more values are the same, or to sort variables according to value. Comparing two values for equality can be particularly tricky, because two variables can hold the same nominal value without necessarily being identical.

A variable containing the empty string (""), for example, will be deemed equal to another variable that has been assigned the value NULL when the equal operator (==) is used for the comparison, but will not be considered to be identical to that variable when the identical operator (===) is used, as illustrated by the following example:

<?php
$str1 = "";
$str2 = NULL;
if ($str2 == $str1) {
echo "\$str2 has the same value as \$str1.<br>";
} // $str2 has the same value as $str1.
else {
echo "\$str2 does not have the same value as \$str1.<br>";
}
if ($str2 === $str1) {
echo "\$str2 is identical to \$str1.<br>";
}
else {
echo "\$str2 is not identical to \$str1.<br>";
} // $str2 is not identical to $str1.
?>

The same situation occurs when we compare numeric values of different types. They may hold the same nominal value, and therefore be considered equal, but they are not considered identical because they have two different datatypes and therefore occupy different-sized chunks of memory.

Whereas an integer is stored as a single value, a floating-point variable is stored as two numbers - the mantissa or significand, which represents the precision of the number (i.e. the sequence of significant digits that comprise the number), and the exponent, which determines the magnitude of the number (basically by indicating where the decimal point goes). For example:

<?php
$flt = 2.0;
$int = 2;
if ($int == $flt) {
echo "\$int has the same value as \$flt.<br>";
} // $int has the same value as $flt.
else {
echo "\$int does not have the same value as \$flt.<br>";
}
if ($int === $flt) {
echo "\$int is identical to \$flt.<br>";
}
else {
echo "\$int is not identical to \$flt.<br>";
} // $int is not identical to $flt.
?>

The comparison of complex data types such as arrays and objects is also possible, although it brings a number of additional complexities into the mix which we will not discuss here. A detailed discussion about how we might go about comparing complex datatypes will be held over until we look in more detail at the datatypes in question.

Best practice

We offer here a few guidelines concerning the use of variables and datatypes that may be of assistance. They are not written in stone, but may help programmers new to PHP or programming in general to avoid some common mistakes:

  • Use appropriate datatypes wherever possible - for example, use integer to store whole number values and float to store floating point values. Remember that PHP assigns a datatype to a variable automatically when a variable is declared, depending on the value assigned to it, so if you intend to declare a floating-point variable with an initial value of 2.0, use $var = 2.0 rather than $var = 2.
  • Use meaningful but concise names for variables - variable names should give some indication about the nature and purpose of the variable without being overly verbose in order to improve readability whilst keeping the amount of typing necessary to a minimum.
  • Use the correct naming conventions for variables. Variable names must start with a dollar sign ($) followed by a lower-case letter or an underscore, and may contain only alpha-numeric characters [A-Z], [a-z] and [0-9]and the underscore character ("_"). Spaces are not allowed, and if a variable name contains more than one word, either each new word should begin with a capital letter (i.e. camel case - our preferred method) or the words should be separated by an underscore character. For example, $myVar or $my_var.
  • Use variables (or constants for values that will never change) rather than hard-coded values. That way, if you need to change a value that is used in multiple locations throughout your code, you only need to make the necessary change in one place.
  • Assign a value of NULL to a new variable if you do not wish it to contain an initial value, or to an existing variable if you wish to clear its current value. Avoid using either zero or the empty string for this purpose, since if these values are inadvertently used somewhere within your code, tracking down the error is going to be more difficult.
  • If working with a resource type variable, make sure the resource is closed when no longer required to prevent potential memory leaks.