Variables and Data Types
Introduction
Variables in PHP are used to store
data that can be used and manipulated throughout your script. PHP is a loosely
typed language, which means you do not need to declare the type of a variable
explicitly. The data type is determined automatically based on the value
assigned.
Variables
A variable in PHP always starts with
a dollar sign $
followed by the variable name. Variable names are case-sensitive and must start
with a letter or underscore.
Example:
<?php
$name
= "Alice";
$age
= 25;
$isAdmin
= true;
?>
Data
Types
PHP supports several data types. The
most common ones include:
String – Represents text.
<?php
$greeting
= "Hello, World!";
?>
Integer – Whole numbers without decimals.
<?php
$year
= 2025;
?>
Float (or Double) – Numbers with decimals.
<?php
$price
= 19.99;
?>
Boolean – Represents true or false.
<?php
$isLoggedIn
= true;
?>
Array – Stores multiple values in a single variable.
<?php
$colors
= ["Red", "Green", "Blue"];
?>
Object – Represents an instance of a class.
<?php
$date
= new DateTime();
?>
Null – Represents a variable with no value.
<?php
$middleName
= null;
?>
Dynamic
Typing
Since PHP is loosely typed, you can
change the type of a variable by assigning a new value of a different type:
<?php
$var
= 10; // integer
$var
= "Ten"; // now a string
?>