Data types are fundamental in understanding programming. In this blogpost we discuss the data types used in PHP. We will also use clear code examples to demonstrate how each data type is used. Let’s dive in!
Data types represent the type of data that can be stored and manipulated in variables. PHP supports several basic data types, including:
They are whole numbers, without a decimal point, like 6212. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions. In PHP, we can declare an integer variable as follows:
Float, also known as a floating-point number or double, represents numbers with decimal points. They like 3.14159 or 49.1. By default, doubles or float print with the minimum number of decimal places needed. As illustrated below.
A string represents a sequence of characters, such as letters, numbers, or symbols. Strings can be enclosed in single quotes ('') or double quotes (""). Here's an example:
Boolean have only two possible values either true or false. PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE. It is often used in conditional statements and comparisons. Here's an example
Arrays are sets of data which can be defined in a PHP Script. Arrays can contain other arrays inside of them without any restriction. Below is an example of an indexed array.
Other type of arrays are Associative arrays and Multidimensional arrays.
Objects are instances of classes and are used in object-oriented programming. An object contains properties (variables) and methods (functions) that define its behavior. Here's a simple example:
Null represents the absence of any value. It is often used to indicate that a variable has no assigned value. NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this − $my_var = NULL;
The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.