PHP: Data Types
Introduction to PHP Data Types
PHP supports several data types that allow you to store different kinds of values in variables. Understanding these data types is crucial for effective PHP programming.
Main PHP Data Types
PHP has eight primitive data types:
- Integer
- Float (floating point numbers - also called double)
- String
- Boolean
- Array
- Object
- NULL
- Resource
1. Integer
An integer is a whole number (without decimals) that can be positive, negative, or zero.
Example:
<?php
$x = 5985;
var_dump($x);
// Output: int(5985)
?>
The var_dump()
function returns the data type and value.
2. Float
A float is a number with a decimal point or a number in exponential form.
Example:
<?php
$x = 10.365;
var_dump($x);
// Output: float(10.365)
?>
3. String
A string is a sequence of characters. It can be enclosed in single quotes ('') or double quotes ("").
Example:
<?php
$x = "Hello world!";
var_dump($x);
// Output: string(12) "Hello world!"
?>
4. Boolean
A Boolean represents two possible states: TRUE or FALSE.
Example:
<?php
$x = true;
var_dump($x);
// Output: bool(true)
?>
5. Array
An array stores multiple values in one single variable.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
// Output: array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
?>
6. Object
An object is an instance of a class. It can store both data and information on how to process that data.
Example:
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}
$myCar = new Car("red", "Volvo");
var_dump($myCar);
// Output: object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }
?>
7. NULL
NULL is a special data type that can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it.
Example:
<?php
$x = null;
var_dump($x);
// Output: NULL
?>
8. Resource
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions.
Because resource variables hold special handles to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
Type Juggling
PHP is a loosely typed language, which means that you don't have to explicitly declare the type of a variable. PHP automatically changes the variable type depending on its value or context.
Example:
<?php
$x = "5"; // $x is a string
$y = $x + 2; // $y is an integer (7)
var_dump($y);
// Output: int(7)
?>
Conclusion
Understanding PHP data types is fundamental to writing effective PHP code. As you progress in your PHP journey, you'll learn how to manipulate these data types and use them in more complex operations.