Please wait

Data Types

Data types in PHP are the types of values that a variable can hold. They determine what kind of information a variable can store and how that information can be manipulated and used.

Why are data types important?

Data types are important in PHP because they determine the type of data that a variable can store and how it can be used in your code. By specifying the data type of a variable, you can ensure that it can only be used in a certain way and prevent unexpected errors from occurring when the code is executed.

For example, consider a scenario where you need to calculate the average of a set of numbers. If you store these numbers with the incorrect data type, you will not be able to perform mathematical operations on them, and the calculation will be incorrect. However, if you store these numbers correctly, you can perform the calculation as expected.

Here's an analogy to help understand the importance of data types: imagine you are cooking a meal and need to measure out ingredients. If you were to use a cup to measure out salt instead of a teaspoon, the amount you would use would be significantly different, and the meal would not turn out as expected. This is similar to how using the wrong data type in your code can result in unexpected results.

By specifying the correct data type, you can ensure that your code will produce the correct results and help to prevent bugs and errors from occurring.

Diving deep

Knowing and understanding the different data types in PHP is important because each data type has its own specific behavior and rules for how it can be used. By using the correct data type for each variable, you can write clear and efficient code that is easier to read and maintain.

You can think of data types as categories for data. Categorizing data allows programming languages to optimize your applications. If a variable stores a number, the program never has to worry about working with dates or random text. In addition, it clarifies the type of data you're working with, which can be helpful with debugging an application.

Statically vs. Dynamically typed languages

With that being said, programming languages tackle data types differently. Generally, there are two types of languages, which are dynamically typed languages and statically typed languages.

In statically typed languages, the variable type must be specified at the time of declaration, and it cannot change later on in the code. This is similar to declaring the type of a container (e.g., a box) that can only hold a specific type of item (e.g., pencils).

In dynamically typed languages, the type of a variable is determined at runtime and can change during the execution of the program. This is similar to using a basket instead of a box to hold items. The basket can hold any type of item, and you can add or remove items as needed.

In general, dynamically typed languages are considered to be more flexible and easier to work with, while statically typed languages are considered to be more secure and efficient. PHP is considered to be a dynamically typed language.

PHP Data Types

In PHP, there are eight basic data types:

  • Integer: A whole number, either positive, negative, or zero.
  • Float: A number with a decimal point, also known as a floating-point number.
  • String: A sequence of characters, such as words or sentences.
  • Boolean: A value that can only be either true or false.
  • Array: An ordered collection of values accessed by index.
  • Object: A data type that can store data and functions as a single unit.
  • Resource: A special type that refers to external resources, such as database connections or file handles.
  • Null: Represents the absence of a value.

In addition to these basic data types, PHP also supports several other data types, such as Callable, Iterable, and Void, which are available in PHP 7 and later versions.

Let's dive into a few of these data types. Some data types will be left out for another lesson.

Integers

The integer data type in PHP is used to store whole numbers. An integer can be either positive, negative, or zero. In PHP, integers can be specified by assigning a number to a variable without any decimals.

Here are some examples of integer values in PHP:

$a = 42;
$b = -100;
$c = 0;
 
 

Floats

The float data type in PHP stores numbers with a decimal point, also known as floating-point numbers. In PHP, floating-point numbers can be specified by simply assigning a number with a decimal point to a variable.

Here are some examples of float values in PHP:

In this example, $a is a simple floating-point number, $b is a negative floating-point number, and $c is a scientific notation representation of a floating-point number.

In general, you should use the float data type whenever you need to store a number with a decimal point, or when you need to perform calculations with numbers that are not whole numbers.

$a = 3.14;
$b = -0.01;
$c = 1.23e5;
 
 

Strings

The string data type in PHP is used to store sequences of characters, such as words or sentences. In PHP, strings can be specified using single or double quotes.

Here are some examples of string values in PHP:

In the example above, $name is a string that contains the name "John Doe" and $greeting is a string that contains the greeting "Hello, World!".

Strings in PHP can contain any combination of letters, numbers, and special characters, and can be of any length.

$name = "John Doe";
$greeting = 'Hello, World!';
 
 
 

Single-quotes vs. double-quotes

It's important to remember that PHP distinguishes between single-quoted and double-quoted strings.

Single-quoted strings are slightly faster and are evaluated more quickly but do not support variable substitution or special escape sequences. Double-quoted strings are slower but allow you to include the values of variables and special characters within the string.

$name = "John Doe";
echo "Hello, $name"; // output: Hello, John Doe
echo 'Hello, $name'; // output: Hello, $name
 
 
 

String Interpolation

The process of inserting a variable into a string is known as string interpolation. There's an alternative syntax for inserting a variable into a string, which is by wrapping the variable with a pair of {} characters.

For example, here's how you can do string interpolation with and without the {} characters.

There are two other options for performing string interpolation, but they're being deprecated. You can read more about that here.

$name = "John Doe";
echo "Hello, $name"; // output: Hello, John Doe
echo "Hello, {$name}"; // output: Hello, John Doe
 
 
 

String Concatenation

String concatenation is the process of joining two or more strings together. In other words, it's a way of sticking strings end-to-end to create a new, larger string.

In PHP, you use the . operator to concatenate strings. Here's an example:

In this example, the strings "Hello, " and "world!" are concatenated (joined together) using the . operator, and the resulting string "Hello, world!" is stored in the variable $greeting.

$greeting = "Hello, " . "world!";
 
 
 

Booleans

The boolean data type in PHP is used to store values that can be either true or false. This data type is often used in conditionals, where a certain piece of code should be executed only if a certain condition is met.

Here are some examples of boolean values in PHP:

In the example above, $is_admin is a boolean variable that is set to true, and $is_logged_in is a boolean variable that is set to false.

$is_admin = true;
$is_logged_in = false;
 
 
 

Null

The null data type in PHP represents the absence of a value. It is used to indicate that a variable has no value assigned to it.

Here are some examples of using null in PHP:

In the example above, $user is a variable that is explicitly set to null, indicating that it has no value.

It's important to keep in mind that null is not the same as false, an empty string, or the integer 0. These values have specific meanings, whereas null represents the absence of a value.

$user = null;
 
 
 
 
 

Getting the data type

You can use the gettype function in PHP to retrieve the data type of a variable. The gettype function takes a single argument and returns a string indicating the type of that argument.

Here are some examples of using the gettype function for different data types in PHP:

$name = "John Doe";
$age = 30;
$weight = 70.5;
$is_admin = true;
$user = null;
 
echo gettype($name);    // Outputs: string
echo "<br>";
echo gettype($age);     // Outputs: integer
echo "<br>";
echo gettype($weight);  // Outputs: double
echo "<br>";
echo gettype($is_admin); // Outputs: boolean
echo "<br>";
echo gettype($user);    // Outputs: NULL

In the example above, the gettype function is used to retrieve the data type of several variables, including a string, an integer, a float, a boolean, and a null value. The output of the gettype function indicates the type of each variable, such as string, integer, double (aka float), boolean, or NULL.

What is the double type?

Numbers with decimal values can be called a float or double. It's a weird quirk of PHP to have two different names for the same data type. Most devs refer to numbers with decimal values as floats instead of doubles.

What is a function?

We haven't had the chance to talk about functions yet. But for now, all you need to know is that functions are another feature for giving instructions to machines. Some functions allow you to pass on additional data inside a pair of parentheses (()).

Exercises

Exercise #1

Try creating a set of variables the current year (integer), price (float), favorite food (string), whether someone has permission (boolean), and an empty inventory (null).

Exercise #2

What is the output of the script?

$name = "John";
 
echo "hello {1}" ; // ?
 
echo "hello {'name'}" ; // ?
 
echo "hello {$name}" ; // ?

Key takeaways

  • Data types in PHP are the types of values that a variable can hold.
  • Categorizing data allows programming languages to optimize your applications.
  • A statically typed language is a programming language where the data type of a value must be explicitly specified by the programmer before the value is used, and the type cannot be changed at runtime.
  • A dynamically typed language is a programming language where the data type of a value is determined at runtime and can change during the execution of a program, without the need for explicit type declaration by the programmer.
  • PHP is a dynamically typed language.
  • Integers allow us to store positive/negative whole numbers.
  • Floats/doubles allow us to store positive/negative numbers with decimals.
  • Strings allow us to store a sequence of characters.
  • String interpolation is a feature for inserting a variable inside a string.
  • Booleans allow us to store a true or false value.
  • The null type allows us to specify that a variable does not have a value.
  • We can get the data type of a variable by using the gettype function.

Comments

Please read this before commenting