The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.
In PHP, as in all programming languages, data types are used to classify one particular type of data. This is important because the specific data type you use will determine what values you can assign to it and what you can do to it (including what operations you can perform on it).
In this tutorial, we will go over the important data types native to PHP. This is not an exhaustive investigation of data types, but will help you become familiar with what options you have available to you in PHP.
One way to think about data types is to consider the different types of data that we use in the real world. Two different types are numbers and words. These two data types work in different ways. We would add 3 + 4
to get 7
, while we would combine the words star
and fish
to get starfish
.
If we start evaluating different data types with one another, such as numbers and words, things start to make less sense. The following equation, for example, has no obvious answer:
'sky' + 8
For computers, each data type can be thought of as being quite different, like words and numbers, so we have to be careful about how we use them to assign values and how we manipulate them through operations.
PHP is a loosely typed language. This means, by default, if a value doesn’t match the expected data type, PHP will attempt the change the value of the wrong data type to match the expected type when possible. This is called type juggling. For example, a function that expects a string
but instead receives an integer
with a value of 2
will change the incoming value into the expected string
type with a value of "2"
.
It is possible, and encouraged, to enable strict mode on a per-file basis. This provides enforcement of data types in the code you control, while allowing the use of additional code packages that may not adhere to strict data types. Strict type is declared at the top of a file:
<?php
declare(strict_types=1);
...
In strict mode, only a value corresponding exactly to the type declaration will be accepted; otherwise a TypeError
will be thrown. The only exception to this rule is that an int
value will pass a float
type declaration.
Any number you enter in PHP will be interpreted as a number. You are not required to declare what kind of data type you are entering. PHP will consider any number written without decimals as an integer (such as 138) and any number written with decimals as a float (such as 138.0).
Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …). An integer can also be known as an int
. As with other programming languages, you should not use commas in numbers of four digits or more, so to represent the number 1,000 in your program, write it as 1000
.
We can print out an integer in a like this:
echo -25;
Which would output:
Output-25
We can also declare a variable, which in this case is a symbol of the number we are using or manipulating, like so:
$my_int = -25;
echo $my_int;
Which would output:
Output-25
We can do math with integers in PHP, too:
$int_ans = 116 - 68;
echo $int_ans;
Which would output:
Output48
Integers can be used in many ways within PHP programs, and as you continue to learn more about the language you will have a lot of opportunities to work with integers and understand more about this data type.
A floating-point number or float is a real number, meaning that it can be either a rational or an irrational number. Because of this, floating-point numbers can be numbers that can contain a fractional part, such as 9.0
or -116.42
. For the purposes of thinking of a float
in a PHP program, it is a number that contains a decimal point.
Like we did with the integer, we can print out a floating-point number like this:
echo 17.3;
Which would output:
Output17.3
We can also declare a variable that stands in for a float, like so:
$my_flt = 17.3;
echo $my_flt;
Which would output:
Output17.3
And, just like with integers, we can do math with floats in PHP, too:
$flt_ans = 564.0 + 365.24;
echo $flt_ans;
Which would output:
Output929.24
With integers and floating-point numbers, it is important to keep in mind that 3
does not equal 3.0
, because 3
refers to an integer while 3.0
refers to a float. This may or may not change the way your program functions.
Numbers are useful when working with calculations, counting items or money, and the passage of time.
A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. This sequence is enclosed within either single quotes ''
or double quotes ""
:
echo 'This is a 47 character string in single quotes.'
echo "This is a 47 character string in double quotes."
Both lines output the their value the same way:
OutputThis is a 47 character string in single quotes.
This is a 47 character string in double quotes.
You can choose to use either single quotes or double quotes, but whichever you decide on you should be consistent within a program.
The program “Hello, World!” demonstrates how a string can be used in computer programming, as the characters that make up the phrase Hello, World! are a string:
echo "Hello, World!";
As with other data types, we can store strings in variables and output the results:
$hw = "Hello, World!"
echo $hw;
Either way, the output is the same:
OutputHello, World!
Like numbers, there are many operations that we can perform on strings within our programs in order to manipulate them to achieve the results we are seeking. Strings are important for communicating information to the user, and for the user to communicate information back to the program.
The Boolean, or bool
, data type can be one of two values, either true
or false
. Booleans are used to represent the truth values that are associated with the logic branch of mathematics.
You do not use quotes when declaring a Boolean value; anything in quotes is assumed to be a string. PHP doesn’t care about case when declaring a Boolean; True
, TRUE
, true
, and tRuE
all evaluate the same. If you follow the style guide put out by the PHP-FIG, the values should be all lowercase true
or false
.
Many operations in math give us answers that evaluate to either True or False:
True
False
True
False
True
False
Like with any other data type, we can store a Boolean value in a variable. Unlike numbers or strings, echo
cannot be used to output the value because a Boolean true
value is converted to the string "1"
, while a Boolean false
is converted to ""
(an empty string). This allows “type juggling” to convert a variable back and forth between Boolean and string values. To output the value of a Boolean we have several options. To output the type along with the value of a variable, we use var_dump
. To output the string representation of a variable’s value, we use var_export
:
$my_bool = 4 > 3;
echo $my_bool;
var_dump($my_bool);
var_export($my_bool);
Since 4 is greater than 3, we will receive the following output:
Output1
bool(true)
true
The echo
line converts the true
Boolean to the string of 1
. The var_dump
outputs the variable type of bool
along with the value of true
. The var_export
outputs the string representation of the value which is true
.
As you write more programs in PHP, you will become more familiar with how Booleans work and how different functions and operations evaluating to either True
or False
can change the course of the program.
The NULL type is an absence of value. It reserves space for a variable. This allows PHP to know about a variable, but still consider it unset. The only possible value of a NULL type is the case-insensitive value of null
. When PHP attempts to access a variable that has not been declared, it will throw a warning:
echo $name;
It warns that the variable is not set, but the code continues to process:
OutputPHP Warning: Undefined variable $name
One common way to prevent this warning is to check that that variable has been set using the isset
function:
if (isset($name)) {
echo $name;
}
This skips the echo entirely and no warning is thrown. A second way to prevent this type of error is to set a placeholder value for a variable such as an empty string:
$name = '';
echo "Hello ".$name;
This will now display Hello
without a name because the value of $name
is an empty string:
OutputHello
Both of these solutions are valid and useful. However, when setting the value of $name
to an empty string, that value is actually set:
$name = '';
if (isset($name)) {
echo "Hello ".$name;
}
This will also display Hello
without a name because the value of $name
is set to an empty string:
OutputHello
As with most challenges, there are multiple solutions. One solution is to set the variable to a null
value. This holds space for that variable and prevents PHP from throwing errors, but still considers the variable “not set”:
$name = null;
echo $name;
if (isset($name)) {
echo "Hello ".$name;
}
The variable is has been “declared” so there will be no error when echo
attempts to access the variable. It will also display nothing because there is no value. The condition will also evaluate to false because the $name
variable is not considered set.
We can use var_dump
to see how PHP evaluates a NULL variable:
$name = null;
var_dump($name);
This shows us that the type is NULL:
OutputNULL
While less common than other variable types, NULL is often used as the return type of a function that performs an action but does not have a return value.
An array in PHP is actually an ordered map. A map is a data type that associates or “maps” values to keys. This data type has many different uses; it can be treated as an array
, list
, hash table
, dictionary
, collection
, and more. Additionally, because array values in PHP can also be other arrays, multidimensional arrays are possible.
In its simplest form, an array will have a numeric index or key
. If you do not specify a key, PHP will automatically generate the next numeric key for you. By default, array keys are 0-indexed, which means that the first key is 0, not 1. Each element, or value, that is inside of an array can also be referred to as an item.
An array can be defined in one of two ways. The first is using the array()
language construct, which uses a comma-separated list of items. An array of integers would be defined like this:
array(-3, -2, -1, 0, 1, 2, 3)
The second and more common way to define an array is through the short array syntax using square brackets []
. An array of floats would be defined like this:
[3.14, 9.23, 111.11, 312.12, 1.05]
We can also define an array of strings, and assign an array to a variable, like so:
$sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp'];
Once again, we cannot use echo
to output an entire array, but we can use var_export
or var_dump
:
var_export($sea_creatures);
var_dump($sea_creatures);
The output shows that the array uses numeric keys
:
Outputarray (
0 => 'shark',
1 => 'cuttlefish',
2 => 'squid',
3 => 'mantis shrimp',
)
array(4) {
[0]=>
string(5) "shark"
[1]=>
string(10) "cuttlefish"
[2]=>
string(5) "squid"
[3]=>
string(13) "mantis shrimp"
}
Because the array is 0-indexed, the var_dump
shows an indexed array with numeric keys between 0
and 3
. Each numeric key
corresponds with a string value
. The first element has a key of 0
and a value of shark
. The var_dump
function gives us more details about an array: there are 4 items in the array, and the value of the first item is a string with a length of 5.
The numeric key of an indexed array may be specified when setting the value. However, the key is more commonly specified when using a named key.
Associative arrays are arrays with named keys. They are typically used to hold data that are related, such as the information contained in an ID. An associative array looks like this:
['name' => 'Sammy', 'animal' => 'shark', 'color' => 'blue', 'location' => 'ocean']
Notice the double arrow operator =>
used to separate the strings. The words to the left of the =>
are the keys. The key can either be an integer or a string. The keys in the previous array are: 'name'
, 'animal'
, 'color'
, 'location'
.
The words to the right of the =>
are the values. Values can be comprised of any data type, including another array. The values in the previous array are: 'Sammy'
, 'shark'
, 'blue'
, 'ocean'
.
Like the indexed array, let’s store the associative array inside a variable, and output the details:
$sammy = ['name' => 'Sammy', 'animal' => 'shark', 'color' => 'blue', 'location' => 'ocean'];
var_dump($sammy);
The results will describe this array as having 4 elements. The string for each key is given, but only the value specifies the type string
with a character count:
Outputarray(4) {
["name"]=>
string(5) "Sammy"
["animal"]=>
string(5) "shark"
["color"]=>
string(4) "blue"
["location"]=>
string(5) "ocean"
}
Associative arrays allow us to more precisely access a single element. If we want to isolate Sammy’s color, we can do so by adding square brackets containing the name of the key after the array variable:
echo $sammy['color'];
The resulting output:
Outputblue
As arrays offer key-value mapping for storing data, they can be important elements in your PHP program.
While a constant is not actually a separate data type, it does work differently than other data types. As the name implies, constants are variables which are declared once, after which they do not change throughout your application. The name of a constant should always be uppercase and does not start with a dollar sign. A constant can be declared using either the define
function or the const
keyword:
define('MIN_VALUE', 1);
const MAX_VALUE = 10;
The define
function takes two parameters: the first is a string
containing the name of the constant, and the second is the value to assign. This could be any of the data type values explained earlier. The const
keyword allows the constant to be assigned a value in the same manner as other data types, using the single equal sign. A constant can be used within your application in the same way as other variables, except they will not be interpreted within a double quoted string:
echo "The value must be between MIN_VALUE and MAX_VALUE";
echo "The value must be between ".MIN_VALUE." and ".MAX_VALUE;
Because the constants are not interpreted, the output of these lines is different:
OutputThe value must be between MIN_VALUE and MAX_VALUE
The value must be between 1 and 10
At this point, you should have a better understanding of some of the major data types that are available for you to use in PHP. Each of these data types will become important as you develop programming projects in the PHP language.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
PHP is a popular server scripting language known for creating dynamic and interactive web pages.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!