Data types are the types of data that a variable can hold. PHP supports several built-in data types, each serving a specific purpose.
• PHP supports several data types, which can be broadly categorized into:-
- Scalar Types (predefined)
- Compound Types (user-defined)
- Special Types
1.) Scalar Types (predefined):-
Scalar types are basic data types that hold a single value. They are predefined in PHP.
‣ There are 4 scalar data types in PHP.
‣ Integer:- Represents whole numbers without a decimal point.
$a = 10;
$b = -25;
‣ Float (Double):- Represents numbers with a decimal point. Also known as float or double.
$a = 10.5;
$b = -3.14;
‣ String:- Represents a sequence of characters. Enclosed in quotes.
$a = "Hello, World!";
$b = 'PHP is fun.';
‣ Boolean:- Represents two possible values: true or false.
$a = true;
$b = false;
2.) Compound Types (user-defined):-
Compound types are user-defined data types that can hold multiple values or a collection of values. They include arrays and objects, allowing for more complex data structures.
‣ There are 2 compound data types in PHP.
‣ Array:- A collection of values of same types.
$a = array(1, 2, 3);
$b = array("apple", "banana", "cherry");
‣ Object:- Instances of classes. Objects encapsulate data and methods.
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}
$car = new Car("red", "Toyota");
3.) Special Types:-
Special types in PHP include data types that do not fall into the scalar or compound categories.
‣ There are 2 special data types in PHP.
‣ Resource:- A reference to an external resource, such as a database connection.
$conn = mysqli_connect("localhost", "user", "password", "database");
‣ NULL:- A special type that represents a variable with no value.
$a = null;