PHP supports several data types, which are essential for storing and manipulating different kinds of information in your programs. Understanding these data types is crucial for effective PHP programming.
Strings are sequences of characters, enclosed in single or double quotes.
$name = "John Doe";
$message = 'Hello, World!';
Integers are whole numbers without a decimal point.
$age = 25;
$year = 2023;
Floats, also known as doubles, are numbers with a decimal point or in exponential form.
$price = 19.99;
$pi = 3.14159;
Booleans represent true or false values.
$isLoggedIn = true;
$hasPermission = false;
Arrays store multiple values in a single variable. PHP supports both indexed and associative arrays.
$fruits = array("apple", "banana", "orange");
$person = array("name" => "Alice", "age" => 30);
Objects are instances of user-defined classes, encapsulating data and behavior.
class Car {
public $brand;
public $model;
}
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->model = "Corolla";
NULL represents a variable with no value assigned.
$emptyVar = NULL;
Resources are special variables that hold references to external resources, such as database connections or file handles.
PHP allows you to convert between data types using type casting. This can be done implicitly or explicitly.
$numString = "42";
$num = (int)$numString; // Explicit casting
$result = $numString + 10; // Implicit casting
PHP provides functions to check the type of a variable:
gettype()
: Returns the type of a variableis_int()
, is_string()
, is_array()
, etc.: Check for specific typesvar_dump()
: Displays structured information about variablesUnderstanding PHP data types is fundamental to writing robust and efficient PHP code. As you progress in your PHP journey, you'll find that proper data type management is crucial for tasks like form handling, database operations, and JSON manipulation.