Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

Variables & Data Types in PHP

In PHP, variables are “boxes” where we can store information. They can hold text, numbers, boolean values (true/false), lists, objects, and more. Data types define what kind of information a variable contains and how that information can be used.

Important to know:
  • All variables in PHP start with the $ sign (e.g., $name).
  • You don't need to explicitly declare the type — PHP is a “loosely typed” language and automatically converts types when needed.
  • You can check the content of a variable using functions like var_dump() or print_r().

String

A string is a sequence of characters (text). In PHP, a string is written using single quotes (' ') or double quotes (" "). Important difference:

Example — simple string

<?php
$message = "Hello, world!";
echo $message; // Output: Hello, world!
?>

Example — interpolation vs literal

<?php
$name = "Ana";

echo "Hello, $name!"; // Interpolation: Hello, Ana!
echo 'Hello, $name!'; // Literal: Hello, $name!
?>

Integer (int)

An integer is a whole number, positive or negative, without decimals. This type is used for:

Example — int variables

<?php
$age = 30;
var_dump($age); // int(30)

$sum = -15;
var_dump($sum); // int(-15)
?>

Example — operations with int

<?php
$a = 10;
$b = 5;

$result = $a + $b; 
echo $result; // 15

$subtraction = $a - $b;
echo $subtraction; // 5
?>

Float (decimal number)

A float (or “double”) is a number that has a decimal part. It is used when higher precision is needed, for example:

Example — float variables

<?php
$price = 19.99;
$height = 1.75;

var_dump($price);     // float(19.99)
var_dump($height);    // float(1.75)
?>

Example — operations with float

<?php
$a = 10.5;
$b = 4.2;

$result = $a * $b;
echo $result; // 44.1
?>

Boolean (true / false)

A boolean can only have two values: true or false. This type is commonly used in conditions and control structures (if, while, etc.).

Example — boolean variables

<?php
$isLoggedIn = true;
$hasPermission = false;

var_dump($isLoggedIn);     // bool(true)
var_dump($hasPermission);  // bool(false)
?>

Example — booleans in if

<?php
$isLoggedIn = true;

if ($isLoggedIn) {
    echo "Welcome back!";
} else {
    echo "Please log in.";
}
?>

Array

An array is a collection of values. In PHP, there are several types of arrays:

Example — indexed array

<?php
$fruits = ["apple", "banana", "orange"];

echo $fruits[0]; // apple
echo $fruits[2]; // orange
?>

Example — associative array

<?php
$user = [
    "name" => "John",
    "email" => "ion@example.com",
    "age" => 25
];

echo $user["name"];  // John
echo $user["email"]; // ion@example.com
?>

Example — multidimensional array

<?php
$class = [
    ["name" => "Ana", "grade" => 9],
    ["name" => "Mihai", "grade" => 8],
    ["name" => "Elena", "grade" => 10]
];

echo $class[0]["name"]; // Ana
echo $class[2]["grade"]; // 10
?>

Null

Null means "no value". A variable can have the value null if it hasn't been set yet or if it has been manually "emptied". This is useful when checking whether a variable contains a value or not.

Example — null variable

<?php
$value = null;

var_dump($value); // NULL
?>

Example — checking null

<?php
$value = null;

if (is_null($value)) {
    echo "The variable has no value.";
}
?>

Constants

A constant is like a variable, but its value cannot be changed once defined. They are used for fixed values, such as the application version, a URL, or configuration data.

Example — define constant

<?php
define("SITE_NAME", "PHP Tutorial");
echo SITE_NAME; // PHP Tutorial
?>

Example — constant with const

<?php
const PI = 3.14;
echo PI; // 3.14
?>

Variables by reference in PHP

In PHP, you can make two variables refer to the same memory location. This means that changing one will automatically affect the other. This is called a variable by reference and is done using the & symbol before the variable.

Why use variables by reference?

Variables by reference are useful when:

Creating a variable by reference

You can create a reference between two variables like this:

<?php
$a = 10;
$b = &$a; // $b becomes a reference to $a

echo $a; // 10
echo $b; // 10

$b = 20; // change $b
echo $a; // 20 — $a changed automatically
?>

Passing variables by reference in a function

References are very useful in functions when we want the original value to be modified:

<?php
function add5(&$number) {
    $number += 5;
}

$x = 10;
add5($x);

echo $x; // 15 — $x was modified inside the function
?>

Important to know:

Use references carefully:

  • if you don't need to modify the original variable or you are not working with large values, it's safer to use standard copying;
  • references can make the code harder to follow if overused;
  • use them only where you clearly need simultaneous modification of values.

Data types and conversions

PHP is a loosely typed language, meaning you don't have to specify the type of a variable. However, we can manually convert a value to another type when needed.

Example — explicit conversions

<?php
$number = "100";        // string
$int = (int)$number;    // converted to integer
$float = (float)$number; // converted to float

var_dump($number); // string(3) "100"
var_dump($int);    // int(100)
var_dump($float);  // float(100)
?>

Example — implicit conversions

<?php
$a = "10";
$b = 5;

$result = $a + $b; 
echo $result; // 15

// PHP automatically converted the string "10" to integer
?>

Best Practices for Variables

To make a project easy to understand and maintain:

Example — best practices

<?php
$productPrice = 50;
$tax = 0.19;
$totalPrice = $productPrice + ($productPrice * $tax);

echo "Total Price: " . $totalPrice;
?>

Practical Exercises

Now that we've learned about variables, data types, and constants, let's put everything together. Below are two larger examples you can copy into a PHP editor to see the results in practice.

Example 1 — Exploring Types with var_dump()

This script creates variables of different types and uses the var_dump() function to display both their type and value.

<?php
// String
$name = "Mary";

// Integer
$age = 25;

// Float
$price = 10.5;

// Boolean
$isActive = true;

// Array
$fruits = ["apple", "pear", "banana"];

// Null
$value = null;

// Display information about each, on separate lines
echo;
var_dump($name);
echo "\n";
var_dump($age);
echo "\n";
var_dump($price);
echo "\n";
var_dump($isActive);
echo "\n";
var_dump($fruits);
echo "\n";
var_dump($value);
echo; ?>

Run this code and observe how PHP displays the type and value. It's an excellent exercise to understand how data is stored and recognized.

🔧 PHP Example: exploring types with var_dump()
<?php
// String
$name = "Mary";

// Integer
$age = 25;

// Float
$price = 10.5;

// Boolean
$isActive = true;

// Array
$fruits = ["apples", "pears", "bananas"];

// Null
$value = null;

// Display information about each variable on separate lines
echo "<pre>";
var_dump($name);
echo "\n";
var_dump($age);
echo "\n";
var_dump($price);
echo "\n";
var_dump($isActive);
echo "\n";
var_dump($fruits);
echo "\n";
var_dump($value);
echo "</pre>";
?>

Example 2 — Constants and Calculations with Variables

In this example, we combine variables and constants to calculate the price of a product with VAT. You'll see how to use const for fixed values and how to perform simple calculations.

<?php
// Define a constant for VAT
const VAT = 0.19;

// Variables for a product
$productName = "Laptop";
$productPrice = 3000;

// Calculate total price with VAT
$totalPrice = $productPrice + ($productPrice * VAT);

// Display the result
echo "Product: " . $productName . "<br>";
echo "Price without VAT: " . $productPrice . " RON<br>";
echo "Price with VAT: " . $totalPrice . " RON";
?>

If you run this code, you will get a small “invoice” showing the product price, both without and with VAT included.

Challenge for you: try modifying the code to add another product (e.g., “Phone” with a price of 2000 RON) and calculate the total for both products.

🔧 PHP Example: constants and calculations with variables
<?php
// Define a constant for VAT
const VAT = 0.19;

// Variables for a product
$productName = "Laptop";
$productPrice = 3000;

// Calculate total price with VAT
$totalPrice = $productPrice + ($productPrice * VAT);

// Display the result with formatted numbers
echo "Product: " . $productName . "<br>";
echo "Price without VAT: " . number_format($productPrice, 2, '.', ',') . " USD<br>";
echo "Price with VAT: " . number_format($totalPrice, 2, '.', ',') . " USD";
?>

🧠 Quiz - Variables & Data Types in PHP

Top