📖 Scenario: Imagine you are creating a simple PHP script to store and display information about a fruit.
🎯 Goal: You will declare variables using the dollar sign, assign values, and then display the values.
📋 What You'll Learn
Declare variables with the dollar sign ($)
Assign string and integer values to variables
Use echo to display variable values
💡 Why This Matters
🌍 Real World
Variables with dollar signs are the basic way to store and use data in PHP scripts, such as in websites or apps.
💼 Career
Understanding variable declaration is essential for any PHP developer to write dynamic and interactive web pages.
Progress0 / 4 steps
1
Declare variables with dollar sign
Create a variable called $fruit and assign it the value "Apple". Also create a variable called $quantity and assign it the value 5.
PHP
Hint
Remember, in PHP, all variables start with a dollar sign ($).
2
Add a variable for price
Create a variable called $price and assign it the value 2.5.
PHP
Hint
Use the dollar sign ($) before the variable name and assign the value with =.
3
Calculate total cost
Create a variable called $total and assign it the value of $quantity multiplied by $price.
PHP
Hint
Use the * operator to multiply variables.
4
Display the total cost
Use echo to display the text: Total cost for 5 Apples is 12.5 using the variables $quantity, $fruit, and $total.
PHP
Hint
Use double quotes "" to include variables inside the string with echo.
Practice
(1/5)
1. Which of the following is the correct way to declare a variable named age in PHP?
easy
A. $age = 25;
B. age = 25;
C. var age = 25;
D. int $age = 25;
Solution
Step 1: Recognize PHP variable syntax
In PHP, all variables must start with a dollar sign ($) followed by the variable name.
Step 2: Check each option for correct syntax
$age = 25; uses $age = 25; which is correct. Options B and C miss the dollar sign, and A uses a type declaration which is not standard in PHP variable declaration.
Final Answer:
$age = 25; -> Option A
Quick Check:
PHP variables start with $ = $age = 25; [OK]
Hint: Always start PHP variables with $ sign [OK]
Common Mistakes:
Forgetting the $ sign before variable name
Using other language syntax like var or int
Trying to declare type explicitly in PHP
2. Which of the following is a syntax error in PHP variable declaration?
easy
A. $1number = 10;
B. $name = "John";
C. $total = 100;
D. $_score = 50;
Solution
Step 1: Understand valid variable names in PHP
Variable names must start with a letter or underscore, not a number.
Step 2: Identify invalid variable name
$1number = 10; uses $1number which starts with a number, causing a syntax error. Other options start with $ followed by letter or underscore, which is valid.