Compound
5. Array
An array can hold multiple values at once.
$array1 = array("apple", "banana", "cherry");
$array2 = ["apple", "banana", "cherry"];
6. Object
An object is an instance of a class. You create objects from classes.
class Fruit {
public $name;
function __construct($name) {
$this->name = $name;
}
}
$apple = new Fruit("Apple");
Special Data Types
7. Resource
A resource is a special variable, holding a reference to an external resource, like a file, a database connection, image canvas areas, etc.
$file = fopen("text.txt", "r");
8. NULL
NULL is a special data type that only has one value: NULL.
$nullVar = NULL;
Checking Data Types
You can use various functions to check a variable's data type, like is_int(), is_float(), is_string(), is_bool(), is_array(), is_object(), is_resource(), and is_null().
$var = "Hello, World!";
if(is_string($var)) {
echo '$var is a string.';
}
Type Casting
You can also convert the data type of variables by type casting.
$int = 1;
$str = (string)$int; // convert integer to string
Type Juggling
PHP is capable of automatically converting a variable from one data type to another, depending on the context in which it is used. This is known as "type juggling".
$var = "3" + 4; // $var becomes integer 7
Data types in PHP allow the language to be quite flexible, but it's crucial to be mindful of the kind of data you're working with to prevent unexpected behavior, especially when dealing with different types of data simultaneously.