PHP - Data Types
PHP supports several data types, allowing for a wide range of operations and data manipulations. Understanding these data types is crucial for writing efficient and error-free code. Here’s a detailed overview of the data types in PHP:
1. Scalar Types
a. Boolean
A boolean represents two possible values: true
or false
.
Example:
php<?php
$flag = true;
$isLoggedIn = false;
?>
b. Integer
An integer is a non-decimal number between -2,147,483,648 and 2,147,483,647 (on a 32-bit system).
Example:
php<?php
$number = 1234;
$negativeNumber = -5678;
?>
c. Float (Double)
A float is a number with a decimal point or a number in exponential form.
Example:
php<?php
$floatNumber = 1.234;
$scientificNumber = 0.1234e4; // 1234
?>
d. String
A string is a sequence of characters.
Example:
php<?php
$text = "Hello, World!";
$multilineText = "This is a
multi-line string.";
?>
2. Compound Types
a. Array
An array stores multiple values in one single variable. Arrays can be indexed or associative.
Example:
php<?php
$indexedArray = array(1, 2, 3, 4);
$associativeArray = array("name" => "John", "age" => 30);
?>
b. Object
An object is an instance of a class. Classes define the structure and behavior (data and functions) that the objects created from the class will have.
Example:
php<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . ".";
}
}
$myCar = new Car("black", "Volvo");
echo $myCar->message();
?>
3. Special Types
a. NULL
The NULL
value represents a variable with no value assigned.
Example:
php<?php
$var = NULL;
?>
b. Resource
A resource is a special variable that holds a reference to an external resource, such as a database connection or a file.
Example:
php<?php
$file = fopen("test.txt", "r");
?>
Type Juggling
PHP is a loosely typed language, meaning it automatically converts variables to the appropriate data type depending on their value and the context in which they are used.
Example:
php<?php
$var = "3.14";
echo $var + 2; // Output: 5.14
?>
Type Casting
You can explicitly convert a variable from one type to another using type casting.
Example:
php<?php
$var = "3.14";
$floatVar = (float)$var;
$intVar = (int)$var;
echo $floatVar; // Output: 3.14
echo $intVar; // Output: 3
?>
Checking Data Types
PHP provides several functions to check the type of a variable:
is_bool()
is_int()
is_float()
is_string()
is_array()
is_object()
is_null()
Example:
php<?php
$var = 42;
if (is_int($var)) {
echo "This is an integer.";
}
?>
Summary
PHP supports several data types, including scalar types (boolean, integer, float, string), compound types (array, object), and special types (NULL, resource). Understanding these types and how to use them effectively is fundamental to writing robust PHP applications.