Notes – Data Types in PHP
In PHP, data types define the kind of data a variable can hold.
PHP is a loosely-typed language, meaning you do not need to declare the data type explicitly.
Types of Data in PHP
PHP has four main data types:
- Scalar Data Types:
- String: Sequence of characters.
- Integer: Whole numbers (positive or negative).
- Float (or double): Decimal numbers.
- Boolean: True or false values.
- Compound Data Types:
- Array: Ordered collection of values.
- Object: Instances of classes.
- Special Data Types:
- NULL: Represents no value or an empty variable.
- Resource: Reference to an external resource (e.g., a database connection).
Scalar Data Types
1. String
- A sequence of characters.
- Defined using single (
') or double (") quotes.
$name = "John";
$greeting = 'Hello!';
2. Integer
- Whole numbers (positive, negative, or zero).
$age = 25;
3. Float (Double)
- Numbers with decimals.
$price = 19.99;
4. Boolean
- Represents either
TRUEorFALSE.
$isAdult = true;
$isActive = false;
Compound Data Types
1. Array
- Ordered collection of values, indexed by numbers or keys.
$colors = array("red", "green", "blue");
$person = ["name" => "John", "age" => 30];
2. Object
- Instances of a class, used for object-oriented programming.
class Car {
public $model;
public function drive() {
echo "Driving the car";
}
}
$myCar = new Car();
$myCar->drive();
Special Data Types
1. NULL
- Represents no value or an empty variable.
$emptyVar = null;
2. Resource
- Refers to an external resource, like a database connection.
$file = fopen("file.txt", "r"); // $file is a resource
Summary of PHP Data Types
| Data Type | Example |
|---|---|
| String | "Hello, World!" |
| Integer | 25 |
| Float | 10.5 |
| Boolean | true, false |
| Array | ["apple", "banana", "cherry"] |
| Object | $person = new Person() |
| NULL | $var = null |
| Resource | $file = fopen("file.txt", "r"); |
