PHP Variables


Variables are one of the most important concepts in PHP. They act as containers for storing data that can be used and manipulated throughout your script. Understanding how to declare and use variables is essential for building dynamic web pages.

What Are Variables in PHP?

A variable is a named storage that holds a value, such as a number, text, or boolean. Unlike some languages, PHP variables are loosely typed, meaning you don’t need to declare their data type — PHP automatically detects it.

<?php
// Declare a variable and assign a value
$name = "Vicky"; // String value
$age = 25;       // Integer value
$height = 5.7;   // Float value

// Display the variables
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Height: " . $height;
?>
  • $name, $age, and $height are variables

  • $ symbol is mandatory for every variable

  • PHP automatically assigns the data type based on the value

Rules for Naming Variables

When creating variables in PHP, follow these rules:

  1. Start with a $ sign.

  2. First character must be a letter or underscore, not a number.

  3. Can contain letters, numbers, and underscores after the first character.

  4. Case-sensitive: $name and $Name are different variables.

  5. Avoid using PHP reserved keywords (like echo, if, while) as variable names.

<?php
$firstName = "Vicky"; // Correct
$_lastName = "Sanjana"; // Correct
$2age = 25; // Incorrect, starts with a number
?>

Assigning Values to Variables

You can assign values using the assignment operator =. PHP supports multiple types of values:

<?php
// String
$city = "Delhi";

// Integer
$year = 2025;

// Float
$price = 49.99;

// Boolean
$isAvailable = true;

// Display the values
echo $city . "<br>";
echo $year . "<br>";
echo $price . "<br>";
echo $isAvailable; // Outputs 1 for true
?>
  • Strings are enclosed in quotes (" or ')

  • Booleans display as 1 for true and nothing for false when printed directly

Variables and Strings

Variables can be included inside strings in PHP. There are two main ways:

1. Using Double Quotes

<?php
$name = "Vicky";
echo "Hello, $name!"; // Variable is parsed inside double quotes
?>

Output:

Hello, Vicky!

2. Using Concatenation

<?php
$name = "Vicky";
echo "Hello, " . $name . "!"; // Concatenate using dot operator
?>

Output:

Hello, Vicky!
  • Double quotes allow variable interpolation

  • Concatenation works with both single and double quotes

Changing Variable Values

PHP variables are mutable, meaning their values can be changed anytime:

<?php
$score = 50; // Initial value
echo "Score: $score<br>";

$score = 75; // New value
echo "Updated Score: $score";
?>
  • Reassigning a value overwrites the previous one

  • No need to declare type again

Variable Scope

Variable scope determines where a variable can be accessed.

1. Local Scope

Variables declared inside a function are local to that function:

<?php
function showMessage() {
    $message = "Hello from function"; // Local variable
    echo $message;
}

showMessage();
// echo $message; // Error: $message not accessible outside
?>

2. Global Scope

Variables declared outside functions are global:

<?php
$globalVar = "I am global";

function displayGlobal() {
    global $globalVar; // Access global variable
    echo $globalVar;
}

displayGlobal();
?>
  • Use global keyword to access global variables inside functions

  • Best practice: minimize global variables for cleaner code

Constants vs Variables

Sometimes you need values that don’t change. PHP provides constants using define():

<?php
define("SITE_NAME", "CodePractice");
echo SITE_NAME;
?>
  • No $ symbol for constants

  • Value cannot be changed once defined

Summary of the Tutorial

PHP variables are containers that store data. They are easy to declare, flexible in type, and can be changed as needed. Key points:

  • Variables start with $ and are case-sensitive

  • PHP automatically detects data types

  • Strings, numbers, floats, and booleans are common types

  • Variables have local and global scopes

  • Use constants for fixed values

Mastering variables is crucial because they form the foundation for storing and manipulating data in PHP.


Practice Questions

  1. Declare a variable $name with your name and $age with your age, then print them in a sentence using echo. Include comments explaining each variable.

  2. Create a PHP file that defines $price = 49.99 and $isAvailable = true. Print both values and include comments explaining the data types.

  3. Write a PHP script that declares $firstName = "Vicky" and $lastName = "Sanjana". Concatenate them to display “Vicky Sanjana” and add comments explaining the concatenation.

  4. Assign a value to a variable $score = 50, print it, then update it to $score = 75 and print the new value. Include comments explaining the reassignment.

  5. Create a PHP function displayMessage() that defines a local variable $message = "Hello" and prints it. Try to access $message outside the function and add comments explaining the scope.

  6. Declare a global variable $globalVar = "I am global" and access it inside a function using the global keyword. Print it with comments explaining the global scope.

  7. Write a PHP script that uses a constant SITE_NAME = "CodePractice" and prints it. Add a comment explaining why constants don’t use $.

  8. Create a PHP file where you define a string variable $city = "Delhi" and print it using double quotes for variable interpolation. Include comments explaining the difference between double quotes and single quotes.

  9. Define three variables $a = 5, $b = 10, $c = 15 and calculate their sum. Print the result with comments explaining each step.

  10. Write a PHP page that declares a float $height = 5.7 and a boolean $isStudent = true, then prints them with appropriate comments explaining how PHP displays boolean and float values.


Go Back Top