Introduction
Variables are one of the most important concepts in PHP. A variable stores information that a program can use, change, and display. For example, you can store a student’s name, employee salary, product price, or total marks in a variable.
In PHP, variable names begin with the dollar sign ($). In this chapter, you will learn how to create variables, follow naming rules, update values, and use variables in practical programs through solved questions. PHP Variables and Naming Rules Practice Questions with Solutions to help you understand the concepts.
Question 1: Create and Display a PHP Variable
Problem Statement: Create a variable named $name and store a student’s name in it. Display the name using PHP.
PHP Solution
<?php
$name = "Rahul";
echo $name;
?>
Sample Output
Rahul
Explanation
$nameis the variable name.=assigns a value to the variable."Rahul"is the string stored in the variable.echodisplays the stored value.
PHP variables begin with $, followed by a valid variable name.
Question 2: Store and Display Different Student Details
Problem Statement: Create three variables to store a student’s name, age, and course. Display all three details.
PHP Solution
<?php
$name = "Priya";
$age = 18;
$course = "PHP";
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Course: " . $course;
?>
Sample Output
Name: Priya
Age: 18
Course: PHP
Explanation
This program creates three variables:
$namestores text.$agestores a number.$coursestores the course name.
The dot (.) operator joins text and variable values into one output string.
Question 3: Follow PHP Variable Naming Rules
Problem Statement: Create valid PHP variables for a student’s name, total marks, and course name.
PHP Solution
<?php
$studentName = "Amit";
$total_marks = 450;
$course2 = "PHP Programming";
echo $studentName . "<br>";
echo $total_marks . "<br>";
echo $course2;
?>
Sample Output
Amit
450
PHP Programming
Explanation
PHP variable naming rules include:
- A variable must begin with
$. - The first character after
$must be a letter or underscore. - A variable name can contain letters, numbers, and underscores.
- A variable name cannot begin with a number.
- Variable names are case-sensitive.
Examples of valid names include $studentName, $_total, and $course2.
Examples of invalid names include $2course and $student-name.
Question 4: Understand Case-Sensitive Variables
Problem Statement: Create two variables named $name and $Name. Store different values in them and display both.
PHP Solution
<?php
$name = "Rahul";
$Name = "Priya";
echo $name . "<br>";
echo $Name;
?>
Sample Output
Rahul
Priya
Explanation
PHP variable names are case-sensitive. This means $name, $Name, and $NAME are treated as different variables.
Use consistent naming conventions to avoid confusion and unexpected results.
Question 5: Change the Value of a Variable
Problem Statement: Create a variable named $city, assign it the value "Delhi", and then change its value to "Mumbai". Display both values.
PHP Solution
<?php
$city = "Delhi";
echo "Original City: " . $city . "<br>";
$city = "Mumbai";
echo "Updated City: " . $city;
?>
Sample Output
Original City: Delhi
Updated City: Mumbai
Explanation
A variable’s value can change while the program runs. Initially, $city stores "Delhi". The next assignment replaces that value with "Mumbai".
After reassignment, the variable holds the new value.
Question 6: Perform Calculations Using Variables
Problem Statement: Store two numbers in variables and calculate their sum, difference, and product.
PHP Solution
<?php
$a = 20;
$b = 5;
$sum = $a + $b;
$difference = $a - $b;
$product = $a * $b;
echo "Sum: " . $sum . "<br>";
echo "Difference: " . $difference . "<br>";
echo "Product: " . $product;
?>
Sample Output
Sum: 25
Difference: 15
Product: 100
Explanation
Variables can store the results of mathematical operations.
$sumstores the addition result.$differencestores the subtraction result.$productstores the multiplication result.
This technique is useful for calculators, billing systems, and salary calculations.
Question 7: Use Variables in a Salary Calculation
Problem Statement: An employee earns a basic salary of ₹25,000 and receives an allowance of ₹5,000. Calculate and display the total salary.
PHP Solution
<?php
$basicSalary = 25000;
$allowance = 5000;
$totalSalary = $basicSalary + $allowance;
echo "Basic Salary: Rs. " . $basicSalary . "<br>";
echo "Allowance: Rs. " . $allowance . "<br>";
echo "Total Salary: Rs. " . $totalSalary;
?>
Sample Output
Basic Salary: Rs. 25000
Allowance: Rs. 5000
Total Salary: Rs. 30000
Explanation
The program stores salary components in separate variables and adds them together.
Keeping separate variables makes the calculation easier to understand and update. Real payroll systems may include additional allowances, deductions, taxes, and other rules.
Question 8: Use Descriptive Variable Names
Problem Statement: Store a product’s name, price, and quantity using meaningful variable names. Calculate the total cost.
PHP Solution
<?php
$productName = "Keyboard";
$productPrice = 800;
$productQuantity = 3;
$totalCost = $productPrice * $productQuantity;
echo "Product: " . $productName . "<br>";
echo "Price: Rs. " . $productPrice . "<br>";
echo "Quantity: " . $productQuantity . "<br>";
echo "Total Cost: Rs. " . $totalCost;
?>
Sample Output
Product: Keyboard
Price: Rs. 800
Quantity: 3
Total Cost: Rs. 2400
Explanation
Descriptive variable names make code easier to read.
For example, $productPrice communicates more information than $p. The total cost is calculated by multiplying the product price by the quantity.
Common naming styles include camelCase ($productPrice) and snake_case ($product_price). Choose one style and use it consistently.
Question 9: Understand Variables Without Initial Values
Problem Statement: Create a variable, assign it a value later, and display the value only after assigning it.
PHP Solution
<?php
$marks = 0;
$marks = 85;
echo "Student Marks: " . $marks;
?>
Sample Output
Student Marks: 85
Explanation
The variable is first initialized with 0 and then updated to 85.
Initializing variables before using them makes your code easier to understand and helps avoid warnings or unexpected behavior caused by undefined variables.
Question 10: Create a Student Result Using Variables
Problem Statement: Store a student’s name and marks in three subjects. Calculate the total and average marks, then display the complete result.
PHP Solution
<?php
$studentName = "Neha";
$english = 80;
$maths = 90;
$computer = 95;
$totalMarks = $english + $maths + $computer;
$averageMarks = $totalMarks / 3;
echo "<h2>Student Result</h2>";
echo "Name: " . $studentName . "<br>";
echo "English: " . $english . "<br>";
echo "Maths: " . $maths . "<br>";
echo "Computer: " . $computer . "<br>";
echo "Total Marks: " . $totalMarks . "<br>";
echo "Average Marks: " . $averageMarks;
?>
Sample Output
Student Result
Name: Neha
English: 80
Maths: 90
Computer: 95
Total Marks: 265
Average Marks: 88.33333333333333
Explanation
The program stores each subject’s marks in a separate variable.
$totalMarksadds the three subject marks.$averageMarksdivides the total by three.echodisplays the student’s result.
If you want to display the average with two decimal places, replace the last output statement with:
echo "Average Marks: " . number_format($averageMarks, 2);
The average will then display as 88.33.
Key Takeaways
- PHP variables begin with the
$symbol. - Use
=to assign a value to a variable. - Variable names must begin with a letter or underscore after
$. - Variable names cannot start with a number.
- PHP variables are case-sensitive.
- Variable values can be updated during program execution.
- Variables can store text, numbers, and calculation results.
- Descriptive names such as
$totalSalaryimprove code readability. - Initialize variables before using them.
- Variables make calculations and dynamic output easier to manage.
Frequently Asked Questions
1. What is a variable in PHP?
A variable is a named storage location used to hold a value that a program can access or change.
2. How do you declare a variable in PHP?
Assign a value to a name beginning with $, such as $name = "Rahul";. PHP does not require a separate variable declaration keyword.
3. Can a PHP variable start with a number?
No. The first character after $ must be a letter or underscore, not a number.
4. Are PHP variable names case-sensitive?
Yes. $age and $Age are different variables.
5. Can I change a variable’s value?
Yes. You can assign a new value to an existing variable at any point in your program.
6. What happens if I use an undefined variable?
PHP may issue a warning and treat the value as null in certain contexts. Initialize variables before using them to avoid unexpected behavior.
7. What is the difference between camelCase and snake_case?
CamelCase uses capitalization to separate words, such as $totalSalary. Snake_case uses underscores, such as $total_salary.
8. Do PHP variables need a declared data type?
No. PHP is dynamically typed, so a variable’s type is generally determined by the value assigned to it.
9. Can a variable store the result of a calculation?
Yes. For example, $total = $price * $quantity; stores the calculated result in $total.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
