PHP Data Types
Last updated onThe whole world of PHP programming revolves around data, be it numbers, text, or more complicated structures. Each of these pieces of information carries a specific type, and for correct operation, PHP has to be aware of what type it is dealing with. To handle this, PHP uses data types—categories that tell PHP how to interpret, store, and finally work with various types of information. Good knowledge of data types in PHP will make your coding efficient and bug-resistant.
Let's look at the most critical PHP data types in some detail; how they work and some samples of using each. By the end of this tutorial, you should have a good working knowledge of integers, strings, booleans, arrays, and a few others. Let's get started!
An Overview of PHP Data Types
PHP has a number of primary types, sometimes known as primitive data types—which include integers, floats, strings, and booleans. These types are foundational, meaning they represent single, undivided values.
PHP data types can be categorized into three types, as shown below:
- Scalar Data Types ( integer - float - string - boolean ).
- Compound Data Types ( array - object - callable - iterable ).
- Special Data Types ( resource - null ).
In the following section, you'll learn about the scalar types in PHP.
Exploring PHP Scalar Types
Scalar types in PHP refer to a restricted set of values that can be assigned to a variable. These include integers, strings, floats, and booleans.
Let’s get started with PHP string types.
PHP String
A PHP string is a series of characters enclosed within single or double quotes. The string’s length should not surpass 256 characters, and PHP lacks native support for Unicode. Strings may be enclosed using either double or single quotation marks.
Strings deal with any text. PHP strings are used constantly, be it usernames, messages, or product descriptions.
Here is a figure showing you the types of PHP strings.
PHP supports four types of string syntax: single-quotes, double-quotes, heredoc, and nowdoc. To explore these in detail, navigate to the PHP string tutorial.
Anyway, In the following PHP code, you will see how to use the four types of PHP strings.
<?php
// => Double Quotes
echo "Double Quotes !"; // Output: Double Quotes !
echo "<br/>";
// => Single Quotes
echo 'Single Quotes !'; // Output: Single Quotes !
echo '<br/>';
// => Heredoc
$heredpoc = <<<IDENTIFIER
This is heredoc string <br/>
IDENTIFIER;
echo $heredpoc; // Output: This is heredoc string
// => Nowdoc
$nowdoc = <<<'EOUT'
This is nowdoc string <br/>
EOUT;
echo $nowdoc; // Output: This is nowdoc string
In the next section, I will explain the data type ‘integer.’ Let’s dive right in.
PHP Integer Data Type
The PHP Integer represents a numeric value that can be assigned to a PHP variable, covering numbers from the set -3, -2, -1, 0, 1, 2, 3. PHP offers four data types for handling integers: decimal, hexadecimal, octal, and binary. For additional information, you can navigate to the PHP Int tutorial.
The example below shows you all types of PHP integers.
<?php
// Decimal
$decimal = 500;
echo $decimal; // output: 500
// Hexadecimal
$hexadecimal = 0x5CB;
echo $hexadecimal; // output: 1483
// Octal
$octal = 0264;
echo $octal; // output: 180
// Binary
$binary = 0b010101;
echo $binary; // output: 21
Let’s move on to PHP float in the section below.
PHP Float
PHP float represents numbers containing decimal points, also known as ‘double’ or ‘real numbers.’ For further information, navigate to the PHP float tutorial.
Let’s take a look at an example.
<?php
// Float
$float = 5.15;
echo $float; // the output: 5.15
Let’s move on to the last scalar type of PHP data, which is the boolean type.
PHP Boolan
Booleans are simple but important; they have two values only: true
and false
. Booleans work in the background in your conditional logic; they help PHP decide whether to run parts of your code. They are like tiny on/off switches.
For example:
<?php
// True Boolean Value
$true = true;
echo $true; // the output: 1
// False Boolean Value
$false = false;
echo $false; // the output:
For additional information about the PHP float data type, please navigate to PHP float tutorial.
In the next section, we will delve into compound data types. Let’s get started.
Understanding the Compound PHP Data Types
We can define compound data types as data that can contain more than one element; each element has a different primitive PHP data type.
Examples of these compound data types include arrays, objects, callables, and iterables. Now, let’s explore each one through a PHP code example.
PHP Array
PHP array is a list or map, encompassing various values organized by an array key. These values can span integers, strings, booleans, or any other data type. The array key can be either a string or a numerical index.
PHP supports two syntaxes for arrays, either [ … ] or array( … ). In the following example, you will see how to implement it in code.
<?php
$array_1 = array( "string", 1, ["data"], true );
print_r($array_1);
// Output:
/*
Array
(
[0] => string
[1] => 1
[2] => Array
(
[0] => data
)
[3] => 1
)
*/
PHP
PHP Object
The PHP object is an instance derived from a PHP class or the primary data structure created by the PHP class. It can be assigned to a variable or invoked using $this
, which already points to a specific object.
Let’s see an example.
<?php
class Car {
private string $model;
public function setModel($model) {
$this->model = $model;
}
}
// The object of this class
$object = new Car();
// Define a new object
$obj = new stdClass();
For more details about PHP objects, please refer to this PHP objects. Anyway, let’s move on to the following section.
PHP Callable
a callable refers to a type of value that can be called as a function. This can include regular functions, methods of an object, anonymous functions, and certain other language constructs. Essentially, anything that can be invoked like a function is considered callable in PHP.
For example:
<?php
function exampleFunction($value) {
echo "Example Function: $value\n";
}
class ExampleClass {
public function exampleMethod($value) {
echo "Example Method: $value\n";
}
}
// Callable functions
$callableFunction = 'exampleFunction';
$callableMethod = [new ExampleClass(), 'exampleMethod'];
// Call the callables
call_user_func($callableFunction, "Hello");
call_user_func($callableMethod, "World");
To learn more about PHP callable, read this PHP callable.
Let’s move on to PHP iterable, which is the last compound type in PHP data types.
PHP Iterable
The concept of PHP iterable first appeared in PHP version 7.1. It is a term that can be employed in the for
loop or foreach
. It accepts arrays or objects and can be utilized as a PHP data type.
In another definition, iterable encompasses anything suitable for use in a loop. Let’s see an example.
<?php
function exact_loop( iterable $data ) {
foreach( $data as $number ) {
echo $number;
}
}
exact_loop( [1,2,3,4,5,6,7,8,9] );
You can learn more about PHP iterables by navigating to this PHP iterables.
Let’s complete the remaining parts of this tutorial, which include the special data types.
Special PHP Data Types
There are two special data types in PHP: Null and Resource. Let’s explore each one with an example.
PHP Resource Data Type
The PHP ‘resource’ type pertains to external accesses, representing various external resources containing information or data that requires manipulation within the main source code. Examples of such resources include database connections, files, documents, streams, and sockets.
Let’s see an example.
<?php
$file = fopen("text", "w");
echo $file; // Resource id #5
echo get_resource_type( $file ); // stream
For additional details about this section, read this tutorial.
Anyway, let’s proceed to the null
data type in PHP.
PHP Null Data Type
The PHP null signifies the absence of a value to an assigned PHP variable, wherein it directly means 'no value'. To check this condition, you can use the built-in PHP function is_null
. Now let's dive into the syntax of the PHP null through a simple code example.
<?php echo null ?> // no value
To delve deeper into this topic, you can navigate to the PHP null tutorial.
By the way, there is another tool that you might want to use to find out the data type in PHP. That tool is called the function gettype
. Now, let's see how to work with this function and get some insight into the types of data within our code in PHP.
Understanding the gettype Function in PHP
The gettype function in PHP is a function that is used to return the name of the type of a variable in a string. It returns the data type of the given variable. The function is quite useful where there is a need to test and handle different types dynamically within your scripts. If you use gettype
, then you would know if a variable is an integer, string, array, object, etc. You can take advantage of that in heavier and more flexible programs.
Let’s see an example.
<?php
$string = "CodedTag.com";
$integer = 55;
$bool = true;
$array = array();
echo gettype($string); // string
echo gettype($integer); // integer
echo gettype($bool); // boolean
echo gettype($array); // array
Let’s summarize it.
Wrapping Up
That's the basis of the PHP data type. We came across primitive data types such as integers, strings, floats, and booleans up to more complex ones like arrays, objects, callables, and iterables. Then come the special two: "null" and "resources" maybe a bit tricky, but they're powerful for keeping your data in check when things get a bit technical.
Using these data types effectively means you'll be writing code ready for just about anything. You have the tools now to ensure your PHP scripts are solid, efficient, and flexible enough to handle whatever task or data they face. With gettype, you even have the added ability to double-check exactly what kind of data you're dealing with, providing even more control as you go.
So, no matter if you're working on a small project or also going to prepare something big, knowing your types in PHP is like having the right key to every lock. Keep this guide handy and learn to be comfortable with each type; you will notice how much more reliable your PHP code will be when taking on whatever's coming up!
Frequently Asked Questions (FAQs)
What Are the Main Data Types in PHP?
How Do I Check a Variable's Data Type in PHP?
Can PHP Automatically Change Data Types?
How Can I Convert Data Types in PHP Manually?
What’s an Array in PHP, and When Should I Use It?
How Do You Use Null in PHP, and When Is It Useful?
What Is a Resource Data Type in PHP?
How Can I Enforce Data Types in PHP Functions?
Is PHP a Loosely Typed Language?