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.
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,
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
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:
- Scalar — these are the simplest data types, not made up of any other data type.
- Compound — these are made up of scalar and possibly other compound data types.
- 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 are simply whole numbers without a fractional part. Examples are
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
$y, assigning them the integers
-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";
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
This is formally known as a typecast — an idea that originates from the C programming language.
A typecast is denoted by writing the name of the type enclosed in parentheses (such as
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
<?php $x = '10'; var_dump($x); $x = (int) $x; var_dump($x);
As is evident, first
$x is a string, but after the cast, it becomes an integer holding the value
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
true if the provided value is an integer, or else
Here's an example:
<?php var_dump(is_int(10)); // true var_dump(is_int(10.0)); // false var_dump(is_int('10')); // false
10.0has a fractional part, which is merely equal to
0, it isn't considered an integer.
Floats, or floating-point numbers, are numbers with a fractional part.
Examples of floats include
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;
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);
And as with integers, we can check whether a value is a float or not via the
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
A string is a very simple idea — a sequence of textual characters.
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
<?php // Single-quoted string isn't processed. echo 'Hello\nWorld!'; // Double-quoted string is processed. echo "Hello\nWorld!";
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.
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.
strlen() function allows us to obtain the length of a given string.
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
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 - 1
$1 - $len
$len * -1
$len - 1.
To retrieve the character at a particular index, we can use what's called bracket notation. This is shown below:
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; echo $greeting; echo $greeting;
Here we log the first, third and last characters of the string
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
<?php $greeting = 'Hello World!'; // Retrieving the last character. echo $greeting[strlen($greeting) - 1];
$greeting[-1]returns the last character of
$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
Consider the code below:
<?php $greeting = 'Hello' . ' World'; echo $greeting . '!';
First we concatenate
' World' and save the result in
$greeting. Next, we echo the concatenation of
$greeting with the string
Just like we saw the
(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);
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);
Finally, to check whether a given value is a string or not, we use the
The snippet below illustrates the usage of
<?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
As with the scalar types, PHP defines four compound types — arrays, objects, callables and iterables.
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.
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.
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 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, "\n"; // Marks of sixth quiz. echo $marks;
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
Here's the syntax of
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;
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
<?php $marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61]; $marks_str = (string) $marks;
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()stands for 'readable'. It simply means that
print_r()prints a readable representation of a given value.
print_r() to print our
<?php $marks = [78, 90, 95, 76, 65, 80, 80, 81, 97, 61]; print_r($marks);
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
$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.
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);
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
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
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 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.
We'll unravel the beauties of iterables in the PHP Iterables unit.
The two special data types provided by PHP are
NULL and the resource type.
The NULL type has only one possible value and that is, trivially,
NULLis 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.
NULLis case-insensitive. Hence, it could be written as
NUll, etc. We'll, however, remain consistent in using
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.
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
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()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
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
'integer' when inspecting an integer value, not
In the case of floats, the difference is more noticeable —
'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";