Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Data Types in PHP

Introduction

In PHP, a data type defines the type of data a variable can hold. PHP supports several types of data, including integers, floats, strings, arrays, objects, and more. Understanding these data types is crucial for effective PHP development.

1. Integer

Integers are whole numbers without any decimal point. They can be positive or negative.

Example of an integer:

$num = 42;

2. Float

Floats, also known as floating-point numbers, are numbers with a decimal point or in exponential form.

Example of a float:

$price = 19.99;

3. String

Strings are sequences of characters, used for text.

Example of a string:

$greeting = "Hello, World!";

4. Boolean

Booleans represent two possible states: TRUE or FALSE.

Example of a boolean:

$is_logged_in = true;

5. Array

Arrays are collections of items stored in a single variable. Each item can be accessed by its index.

Example of an array:

$colors = array("Red", "Green", "Blue");

6. Object

Objects are instances of classes, which can contain both data (properties) and functions (methods).

Example of an object:

class Car {
    function Car() {
        $this->model = "VW";
    }
}
$myCar = new Car();
echo $myCar->model;
                

7. NULL

NULL is a special data type that represents a variable with no value.

Example of NULL:

$var = NULL;

8. Resource

Resources are special variables that hold references to external resources, such as database connections.

Example of a resource:

$handle = fopen("file.txt", "r");

Conclusion

Understanding the various data types in PHP is fundamental for writing robust and efficient code. Each data type serves a specific purpose and knowing when to use each one will help you in your PHP development journey.