PHP Data Types
PHP Data Types
Understanding PHP Data Types
In our initial exploration of PHP, we've already encountered the concept of storing information in variables. For example, we might store a name as text and a score as a number. These pieces of information belong to different categories called data types. PHP, like most programming languages, provides a set of built-in data types to represent various kinds of data. There are ten fundamental data types in PHP, which we can broadly classify into scalar, compound, and special types. This lesson will focus primarily on the most commonly used data types.
Let's take a quick look at the list of PHP data types:
- String
- Integer
- Float
- Boolean
- Resource
- Iterable
- Callable
- Object
- Array
- NULL
We’ll concentrate on the first four, known as scalar data types, which represent single values. We’ll also cover the NULL type. Later on, you'll delve into compound data types like arrays and objects, and we'll briefly mention the less common special types.
Scalar Data Types in Detail
Let's break down those core scalar data types:
- String: Represents textual data. Think of names, addresses, or any sequence of characters. For instance,
"Hello, world!"is a string. - Integer: Represents whole numbers, without any decimal component. Examples include
-5,0, and100. - Float: Represents numbers that do have a decimal component. These are also known as floating-point numbers. Examples include
3.14,-2.7, and0.5. - Boolean: Represents truth values. A boolean can only be one of two values:
trueorfalse. This is incredibly useful for controlling program flow (e.g., checking if a user is logged in).
Finally, we have NULL, which represents the absence of a value.
Exploring Data Types Interactively
To get a feel for how these data types work, let's use PHP's interactive mode. This is a convenient way to test out individual lines of PHP code and see the results immediately, without needing to create a full PHP file.
To enter interactive mode, simply type php -a in your terminal or command prompt. You're now ready to experiment!
Let's try a simple example:
php > $username = "matt";
php > print gettype($username);
string
In this example, we assign the string "matt" to a variable named $username. Then, we use the gettype() function to determine the data type of the variable. As you can see, it correctly identifies $username as a string. This interactive approach will be invaluable as we continue to explore PHP.
PHP Data Types: Numbers and Booleans
Let's revisit the concept of data types using a simple example. We'll assign the string value "matt" to a variable named $username. Then, we'll use PHP's built-in gettype() function to determine and display the variable's data type. This will confirm that $username holds a string value.
If you’re familiar with programming languages like Java or C#, you’re probably used to explicitly declaring the data type of a variable. PHP handles this differently. It's a loosely typed language, meaning a single variable can hold values of various data types over time. PHP automatically figures out the data type based on the value assigned to it.
While it's possible to explicitly define data types in PHP (we'll explore this in more detail later, when we start writing functions), for now, we'll rely on PHP's automatic type inference for our simple variable assignments.
Let's look at numeric data types. You can assign whole numbers (like 21) or numbers with decimal points (like 9.99) to variables, and PHP will interpret them correctly.
<?php
$age = 21;
echo gettype($age); // Output: integer
$price = 9.99;
echo gettype($price); // Output: double
?>
Notice that $age is recognized as an integer, and $price is recognized as a double. It’s important to understand that although gettype() returns "double" for floating-point numbers, PHP only has one underlying floating-point data type: float. The "double" return value from gettype() is a historical artifact from PHP’s origins as an older language, referencing the double-precision floating-point format used internally. Don’t be concerned with the distinction; all floating-point numbers in PHP are fundamentally floats.
Now, let's examine the bool data type, which represents true/false values.
<?php
$isDutyFree = true;
echo gettype($isDutyFree); // Output: boolean
echo $isDutyFree; // Output: 1
?>
When you use gettype() on the $isDutyFree variable, you’ll see "boolean" displayed. PHP uses the alias "boolean" for the bool data type, and while they are largely interchangeable, it's best practice to consistently use bool in your code. I’ll do so in this guide.
A curious observation arises when you try to print the value of $isDutyFree. Instead of "true," you see the number 1. This isn't an error; it's how PHP represents boolean values when displaying them. true is equivalent to 1, and false is equivalent to 0.
Displaying Boolean Values and Introducing NULL
When using the print function in PHP, the engine automatically converts any value you provide into a string. Boolean values are handled in a specific way during this conversion: true becomes the string "1", while false transforms into an empty string (represented as ""). This automatic conversion can sometimes obscure the actual boolean value.
To accurately determine the data type and value of a boolean variable, use the var_dump() function. This function provides detailed information about a variable, including its type and its value. It's a valuable tool for learning PHP and for identifying issues in your code.
For example:
<?php
$isDutyFree = true;
var_dump($isDutyFree);
?>
This code will output: bool(true), confirming that $isDutyFree is indeed a boolean and its value is true.
Understanding the NULL Data Type
PHP also includes a special data type called NULL. It represents the absence of a value. You can use either NULL or null (case doesn't matter) to denote this type. A variable can be considered NULL in a few situations.
Firstly, if a variable hasn't been assigned a value yet, attempting to inspect it with var_dump() will generate a warning indicating the variable is undefined, followed by the NULL value.
Secondly, a variable is assigned the NULL value when you explicitly set it to NULL:
<?php
$firstName = NULL;
var_dump($firstName);
?>
This will output: NULL.
It's important to distinguish between a variable that hasn't been assigned a value (resulting in a warning from var_dump()) and a variable that has been explicitly assigned the value NULL. Both ultimately represent an absence of a meaningful value, but the way PHP handles them in terms of warnings differs. Assigning a variable the value NULL is perfectly valid and functions similarly to assigning it any other data type.
Understanding PHP Data Types and Null Values
In PHP, every piece of data you work with is associated with a data type. These types dictate the kind of operations you can perform and how PHP interprets the data. While we’re already familiar with common types like strings, integers, and booleans, it's crucial to understand how PHP handles situations where a variable doesn't hold a meaningful value. This often manifests as NULL.
A variable becomes NULL when it’s explicitly cleared. You can accomplish this using the built-in unset() function. When a variable is NULL, it essentially behaves as if it never existed. Attempting to display a NULL variable will result in a warning indicating an undefined variable.
<?php
$lastName = "Smith";
var_dump($lastName); // Output: string(5) "Smith"
unset($lastName);
var_dump($lastName); // Output: Warning: Undefined variable $lastName in ...
// NULL
?>
In more complex applications, you're likely to encounter NULL values. For example, a database connection might fail and be assigned NULL, or a function might be expected to return an object, but that object doesn’t exist. We’re going to explore how to handle these situations in later sections when we delve into object-oriented programming and database interactions. Properly accounting for NULL values is a vital skill for writing robust PHP code.
Checking Variable Data Types
PHP provides a suite of functions that allow you to determine the data type of a variable. These functions return either true or false, depending on whether the variable matches the specified type. This is extremely useful for validating data or ensuring that you're performing operations that are appropriate for the variable's type.
Some of the most commonly used type checking functions include: is_string(), is_int(), is_float(), is_bool(), and is_null(). Let’s look at a few examples:
<?php
$gpa = 3.5;
var_dump(is_string($gpa)); // Output: bool(false)
var_dump(is_int($gpa)); // Output: bool(false)
var_dump(is_float($gpa)); // Output: bool(true)
$middleName = NULL;
var_dump(is_bool($middleName)); // Output: bool(false)
var_dump(is_null($middleName)); // Output: bool(true)
?>
In the example above, $gpa holds a floating-point number (a number with a decimal). Consequently, only is_float() returns true. Conversely, $middleName explicitly holds the NULL value, which is correctly identified by is_null(). These functions provide a reliable way to verify data types and write safer, more predictable code.