PHP Data Types

Chapter 7 36 mins

Learning outcomes:

  1. What are data types
  2. Scalar, compound and special data types
  3. Integers, floats, strings and Booleans
  4. Arrays, objects, callables and iterables
  5. The NULL type
  6. The resource type
  7. The gettype() function

Introduction

Every programming language allows us to work with data. This data can fall into one of many categories of data, such as integers, floats, strings, Booleans, and so on.

Different languages come up with different classifications of data.

For instance, some might provide two separate types for integers and floats, for e.g. C, whereas some might just provide a single type for both of them, for e.g. JavaScript. It all depends on the language under consideration.

PHP, as we shall see in this chapter, provides multiple types of data to the programmer, some of which we have already explored slightly in the previous chapters, while some which we will discover for the first time here.

So let's begin...

What are data types?

In simple terms,

A data type describes a set of values and the operations possible on those values.

For instance, a very common data type in programming languages is the integer type.

We all know that the possible values of integers in maths ranges from negative infinity all the way to positive infinity, whereby each number is a whole number (i.e without a fraction).

However, in the realms of machines, integers are finite. We can only have a bunch of them. Even if the underlying mechanism of storing integers changes and we can store arbitrarily long integers, such as in Python, we are still limited by the total amount of memory available on the machine.

In short, there is finiteness to integers in computing.

Anyways, coming back to the integer type, if it is unsigned and consumes 4 bytes of memory per value, then the range of values possible is 0 to 4294967295.

Apart from these values, the integer type also represents the possible operations that we can carry out on these values. Examples are addition, subtraction, multiplication, division, exponentiation, modulo, and so on.

To boil it down, a data type is an abstract idea that helps us group data according to its value and the whole set of operations possible on that value.

Sometimes a data type could represent just one single value with possibly no operations capable to be performed on that data. PHP has one such type, just as many as other languages do — the NULL type — we'll see that in a while.

Now that the definition is clear, it's time to explore the main data types of PHP.

Classifications of data types

There are three classifications of data types in PHP:

  1. Scalar — these are the simplest data types, not made up of any other data type.
  2. Compound — these are made up of scalar and possibly other compound data types.
  3. Special — these are special types that aren't scalar, nor compound.

Note that these are the classifications of the data types of PHP; they are actually not the data types per se.

The four scalar data types are: integers, floats, strings, Booleans.

And here are all the compound types: arrays, objects, callables, iterables.

Finally, the two special types are: resources, and NULL.

Scalar types — the simple ones

PHP has four scalar types — integers, floats, Booleans, and strings. Let's start off by exploring integers before moving over to consider other scalar types.

Integers

Integers are simply whole numbers without a fractional part. Examples are -100, -1, 0, 1, 100 and so on.

An integer in PHP is signed and is 8 bytes large on a 64-bit machine, and 4 bytes large on a 32-bit machine. The internal implementation is the usual 2's complement used all over computing to represent integral values.

The set of operations that can be performed on integers are all the standard ones — addition, subtraction, multiplication, division, and so on.

Let's see some examples.

In the code below, we define two variables $x and $y, assigning them the integers 10 and -10000, respectively. Next up, we perform and echo the results of a couple of operations on these integers:

<?php

$x = 10;
$y = -1000;

echo '$x + $y: ', $x + $y, "\n";
echo '$x - $y: ', $x - $y, "\n";
echo '$x * $y: ', $x * $y, "\n";
echo '$x / $y: ', $x / $y, "\n";
$x + $y: -990 $x - $y: 1010 $x * $y: -10000 $x / $y: -0.01

This is simple, isn't it?

As we saw back in the PHP Basics chapter, it's possible to convert a given value to an integer by preceding the value with (int).

This is formally known as a typecast — an idea that originates from the C programming language.

A typecast tries to cast (convert) a given value to another one.

A typecast is denoted by writing the name of the type enclosed in parentheses (such as (int), where int is the name of the integer data type), followed by the value to cast.

In the code below, we have a string '10' holding the number 10 inside it:

<?php

$x = '10';

The goal is to convert this string into a number so that we can reliably use it in arithmetic expressions.

The way we do so is by using an integer typecast on $x, as shown below:

<?php

$x = '10';
$x = (int) $x;

Let's test the types of $x before the cast and after it using var_dump():

<?php

$x = '10';
var_dump($x);

$x = (int) $x;
var_dump($x);
string(2) "10" int(10)

As is evident, first $x is a string, but after the cast, it becomes an integer holding the value 10.

This is just remarkable!

Besides conversion, another functionality that commonly pops up in programs is to determine whether a given value belongs to a certain type. This is especially the case with dynamically-typed languages, where a variable can hold anything.

In the case of integers in PHP, to check whether a given value is an integer or not, we use the is_int() function.

is_int() returns true if the provided value is an integer, or else false.

Here's an example:

<?php

var_dump(is_int(10)); // true
var_dump(is_int(10.0)); // false
var_dump(is_int('10')); // false
bool(true) bool(false) bool(false)
Since 10.0 has a fractional part, which is merely equal to 0, it isn't considered an integer.

Floats

Floats, or floating-point numbers, are numbers with a fractional part.

Examples of floats include -3.578, -2.1333333, 0.0, 10.5, 154848.00000004 and so on.

A float in PHP is represented using the standard IEEE-754 double-precision floating-point format that is used across all modern languages today. Following this standard, a float value consumes 8 bytes of memory.

A float is comprised of three things: a sign, a magnitude and an exponent. In mathematical terms, this is similar to the scientific notation we use in our calculations such as -9.81 x 102 (where the sign is -, the magnitude is 9.81 and the exponent is 2).

Time to see some code examples...

In the code below, we create two floating-point numbers and echo their sum:

<?php

$f1 = 3.55;
$f2 = -0.62;

echo $f1 + $f2;
2.93

Quite elementary.

Moving on, to convert a given value to a float, we can use the (float) typecast as illustrated below:

<?php

$x = '10';
var_dump($x);

$x = (float) $x;
var_dump($x);
string(2) "10" float(10)

And as with integers, we can check whether a value is a float or not via the is_float() function.

An illustration is shown below:

<?php

var_dump(is_float(10)); // false
var_dump(is_float(10.0)); // true
var_dump(is_float('10.0'));  // false
bool(false) bool(true) bool(false)

Strings

A string is a very simple idea — a sequence of textual characters.

That's it!

As we know from the last chapters, a string in PHP can be denoted in two ways i.e. by using a pair of single quotes ('') or a pair of double quotes ("").

A pair of single quotes ('') creates a string exactly as it is written — no processing involved within the content of the string. In contrary to this, a pair of double quotes ("") creates a string that is processed for escape sequences and interpolation.

Consider the code below where we demonstrate this difference between '' and "" strings:

<?php

// Single-quoted string isn't processed.
echo 'Hello\nWorld!';

// Double-quoted string is processed.
echo "Hello\nWorld!";
Hello\nWorld Hello World!

In the first output, the \n appears as it is i.e. it isn't considerd as a newline but rather as the \ character followed by n. However, in the second output that results from a double-quoted string, the \n is considered as a newline.

We've already seen escape sequences before, but not interpolation. Interpolation will be discussed in detail in the PHP Strings unit.

Moving on, we're very often interested in obtaining the total number of characters of a given string. Well, this idea has a special name to it.

The total number of characters in a string is referred to as its length.

The strlen() function allows us to obtain the length of a given string.

strlen(string)

Here, string is the string value whose length we want to determine. The function returns the length as an integer.

Apart from the length of a string, another term that pops up quite commonly when working with strings is that of an index. Let's see what is it...

Each character in a string is associated with an incremental position, beginning at 0. This position is formally known as the character's index. Indexes typically begin at 0.

Hence, the first character in a PHP string is at index 0, the second is at index 1, the third is at index 2, and so on and so forth.

Try to devise a formula for the last character's index of a given string. Suppose that the length of the string is stored in the variable $len.

  • $len
  • $len - 1
  • $1 - $len
  • $len * -1
The index of the last character of a given string is 1 less than the length of the string. Hence, the correct formula would be $len - 1.

To retrieve the character at a particular index, we can use what's called bracket notation. This is shown below:

string[index]

string is the string value whose character we want to retrieve while index is the index of that character.

Let's see an example:

<?php

$greeting = 'Hello World!';

echo $greeting[0];
echo $greeting[2];
echo $greeting[11];
Hello\nWorld Hello World!

Here we log the first, third and last characters of the string $greeting, respectively.

If you noticed one thing in the code above, it's that we referred the last character of $greeting by hard coding its index 11. A much better approach would be to keep it flexible so that if the string changes later on, we still correctly access its last character and not any other.

And to make it flexible, we just need to use the length of the string in the computation as described above (in the short quiz).

Consider the code below, where we access the last character of $greeting with the help of strlen():

<?php

$greeting = 'Hello World!';

// Retrieving the last character.
echo $greeting[strlen($greeting) - 1];
!
As of PHP 7.0.1, it's possible to use negative indexes to refer to the nth character from the end of a string. For instance, $greeting[-1] returns the last character of $greeting, $greeting[-2] returns the second last character, and so on. We'll explore negative indexes in more detail in the PHP Strings Basics chapter.

As far as the set of operations of strings in PHP is concerned, the most common operation is that of concatenation. Concatenation is the joining of two strings into one single string.

In PHP, it's done using the . operator.

Consider the code below:

<?php

$greeting = 'Hello' . ' World';
echo $greeting . '!';
Hello World!

First we concatenate 'Hello' with ' World' and save the result in $greeting. Next, we echo the concatenation of $greeting with the string '!'.

Simple.

Just like we saw the (int) and (float) typecasts above to convert an arbitrary value in PHP to an integer and a float, respectively, we can use the (string) typecast to do so for strings.

Shown below is an example:

<?php

$x = 10;
var_dump($x);

$x = (string) $x;
var_dump($x);
int(10) string(2) "10"

There's another way as well: concatenate the value with an empty string (''). The concatenation results in the non-string value to be implicitly converted to a string.

Shown below is an example:

<?php

$x = 10;
var_dump($x);

$x = $x . '';
var_dump($x);
int(10) string(2) "10"

Finally, to check whether a given value is a string or not, we use the is_string() function.

The snippet below illustrates the usage of is_string():

<?php

var_dump(is_string(10)); // false
var_dump(is_string(10.5)); // false
var_dump(is_string('10')); // true
var_dump(is_string("\n")); // true
var_dump(is_string(true)); // false
bool(false) bool(false) bool(true) bool(true) bool(false)

Compound types

As with the scalar types, PHP defines four compound types — arrays, objects, callables and iterables.

Arrays

Arrays are one of the most fruitful concepts in programming to help us work with sequences of data in a highly convenient and intuitive manner.

An array is a compound type hence it's made up of the scalar types we defined above and possibly other compound types. Moreover, it supports a handful of highly useful operations such as searching and sorting.

But what exactly is an array? Well, let's see.

An array is an ordered sequence of elements stored as a single entity in memory.

Since an array is a sequence of arbitrary values, akin to a string that is a sequence of characters, the concepts of length and index also apply to arrays.

In particular, the length of an array is the total number of items in it, whereas the index of an item is the position of that item in the array. Indexes begin at 0, and increase by 1.

Let's now see an example of when to use an array.

Suppose we want to store the marks of a user in ten online quizzes and then sort them. Such a problem can easily be solved by a compound data structure such as an array.

Problems of this kind can't be solved using mere individual variables without an impossible amount of manual coding! Try to think why.

We'll explore more details about the exact purpose of using arrays in the PHP Arrays — Basics chapter.

Anyways, time to create and work with arrays in PHP.

To create an array, we use a pair of square brackets ([]). On their own, these brackets denote an empty array, i.e an array without any items in it.

Thus, in the following code, $arr is an empty array:

<?php

$arr = [];

To add items to an array right at the point when creating it, we put the items inside the brackets. Multiple items are separated using commas (,).

In the code below, we store the marks obtained by a student in his recent ten online programming quizzes inside an array:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];

In source code, an array value denoted using [] is referred to as an array literal.

Likewise, in the code above, [78, 90, 95, 76, ...] is an array literal. And so is the empty array assigned to $arr above, i.e. [] is an array literal as well.

Anyways, after populating an array with data, we might need to retrieve that data. To do so, we use the same notation used to access a character from a string, i.e. the bracket notation.

Let's review the notation albeit for arrays:

array[index]

array is the array under consideration and index is the index of the item in the array that we want to retrieve.

In the following snippet, we echo the marks obtained in the third and sixth quizzes:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];

// Marks of third quiz.
echo $marks[2], "\n";

// Marks of sixth quiz.
echo $marks[5];
95 80

Superb!

To add items to an array after it has been created, we ought to use array functions.

Typically, items are added to the end of the array — an action usually known as pushing an item to an array. And that's done by the array_push() function.

Here's the syntax of array_push():

array_push($array, $item)

The first argument is the array where to add the data whereas the second argument is the data itself. Simple, isn't it?

Let's say that the student, we talked about earlier, takes one more quiz and now we ought to add his score in that quiz to the $marks array as well. To do this, we can use the array_push() function, as shown below:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];

// Add the 11th score to $marks.
array_push($marks, 100);

It's all great to work with arrays, adding items right when defining them, or adding them later on using array_push(). However, we can't visualize whatever is happening inside arrays until and unless we print them.

Now the issue is that echo doesn't accept arrays — if we do something like the following, we get a warning:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];

echo $marks;
Warning: Array to string conversion in <path> on line 5 Array

Precisely speaking, it's not about echo that we get the warning; instead, an array in PHP can't be converted to a string, and whenever we try to do so, we get a warning.

This is illustrated below, by applying the (string) typecast on $marks:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];

$marks_str = (string) $marks;
Warning: Array to string conversion in <path> on line 5

Anyways, coming back to the printing of an array via echo, the question remains: How to print an array in PHP?

Well, PHP has got us covered. It provides a dedicated function to print a readable representation of an array, showcasing all its items. That function is print_r().

The 'r' in print_r() stands for 'readable'. It simply means that print_r() prints a readable representation of a given value.

Let's use print_r() to print our $marks array:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];

print_r($marks);
Array ( [0] => 78 [1] => 90 [2] => 95 [3] => 76 [4] => 65 [5] => 80 [6] => 80 [7] => 81 [8] => 97 [9] => 61 )

See how print_r() outputs each of the items of $marks on a newline, starting with the index of that item.

You'll be using print_r() quite a lot in your programs when dealing with arrays in order to effectively see all the elements at a given instant.

Moving on, uptil this point, we have merely stored data in an array and retrieved data out of it — not really anything jaw-dropping here. Programs that use arrays typically don't just store and retrieve values; they process them.

One common operation performed on arrays is that of sorting. We can use the function sort() to sort an array.

The syntax of sort() follows:

sort($array)

$array is the array to sort. The sort() function doesn't return the sorted array; rather it changes it in-place, i.e. the actual array passed into the function is modified.

We'll learn more about in-place mutations in the PHP Arrays unit.

Let's go ahead and sort the $marks array we created above and then print it:

<?php

$marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61];
sort($marks);

print_r($marks);
Array ( [0] => 61 [1] => 65 [2] => 76 [3] => 78 [4] => 80 [5] => 80 [6] => 81 [7] => 90 [8] => 95 [9] => 97 )

And here we have some array goodness in action!

As with all the data types discussed before, to check if a given value is an array or not, we use the is_array() function.

Shown below is an example:

<?php

var_dump(is_array(10)); // false
var_dump(is_array(10.0)); // false
var_dump(is_array('[1, 2, 3]')); // false
var_dump(is_array([1, 2, 3])); // true
bool(false) bool(false) bool(false) bool(true)

Objects

The remaining three compound types — objects, callables, and iterables — require certain concepts that we haven't explored yet and hence we would defer their details to the later chapters of this course.

Objects are the cornerstone of the object-oriented paradigm that's very maturely supported by PHP. Creating objects via classes and then working with OOP concepts is all a bit more technical than what we have been considering thus far in this course.

We'll discover more about objects and OOP, in general, in the PHP Objects unit.

Callables

Callables are simply values that can be called.

The most common kind of callables used in PHP is that of functions. Ideas such as closures, lexical scoping, free variables, first-class citizens, and so on, are all tied to functions.

We'll explore functions in extreme detail in the PHP Functions unit.

Iterables

Iterables allow us to abstractly create sequences by defining the code to generate the next item in them. Iterables aren't just an argot of PHP — they exist in many other languages such as Python, JavaScript, C++ and so on.

We'll unravel the beauties of iterables in the PHP Iterables unit.

Special types

The two special data types provided by PHP are NULL and the resource type.

NULL

The NULL type has only one possible value and that is, trivially, NULL.

NULL is used to represent the absence of a value.

For instance, after performing a computation, we might want to set a variable to NULL. Some PHP functions return NULL to signify the failure of an operation.

For you, at least, in these early stages of learning, NULL might not be the most useful data type (or value). It's only once you learn about complex ideas that NULL would start proving itself as a useful entity.

NULL is case-insensitive. Hence, it could be written as NULL, null, Null, NUll, etc. We'll, however, remain consistent in using NULL.

Resources

Resources in PHP are values literally representing given resources, such as files, streams, database connections, and so on.

Resources are an advanced concept in PHP and, henceforth, will be covered later in this course.

The gettype() function

var_dump() plays a very good role at describing both the type and the value of a given piece of data. It prints the respective information without us having to manually echo anything.

However, if we only want the type of the data and not necessarily automatically print it, PHP provides us with a function just for that — gettype().

The gettype() function returns the type of a given value in the form of a string.

Note that for a given value, the return value of gettype() might not be the same as the name of the respective value's type in its corresponding is_type() function.

For instance, for an integer, we know that the type-checking function is called is_int() where the name of the underlying type is simply int. However, gettype() returns 'integer' when inspecting an integer value, not 'int'.

In the case of floats, the difference is more noticeable — gettype() returns 'double' when inspecting a float. Why?

Well, simply because of backwards compatibility with old versions of PHP where instead of float, PHP used the term double (following from the term 'double-precision').

An example follows:

<?php

echo gettype(10), "\n";
echo gettype(10.0), "\n";
echo gettype('Hello World!'), "\n";
echo gettype(""), "\n";
echo gettype(true), "\n";
echo gettype(false), "\n";
echo gettype([]), "\n";
echo gettype(NULL), "\n";
integer double string string boolean boolean array NULL