creating variables and displaying them

Part of the course: PHP Practical Learning

creating variables and displaying them

Table of Contents

PHP: Creating Variables and Displaying Them (Practical Tutorial)

  1. Introduction to PHP Variables

  2. Requirements and Setup (XAMPP / Local Server)

  3. PHP Syntax Basics

  4. Declaring Variables in PHP

  5. Rules for Naming Variables

  6. Common Data Types (String, Integer, Float, Boolean)

  7. Assigning Values to Variables

  8. Displaying Variables Using echo

  9. Displaying Variables Using print

  10. Combining Text and Variables

  11. Using HTML with PHP Variables

  12. Practical Examples and Exercises

  13. Common Mistakes and How to Avoid Them

  14. Summary and Best Practices

 

Introduction to PHP Variables

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, variables are one of the most important concepts you need to learn. A variable in PHP is used to store data that can be reused and changed while the script is running. This makes your code more dynamic, flexible, and easier to manage.

In PHP, every variable starts with a dollar sign ($), followed by the variable name. The value is assigned using the equals sign (=).

Basic Structure of a PHP Variable

$variableName = value;

For example, in php Creating Variables and Displaying Them, you might store a name in a variable:

<?php
$name = "Ali";
?>

Here:

  • $name is the variable

  • "Ali" is the value stored in the variable

Displaying Variables in PHP

A key part of php Creating Variables and Displaying Them is showing the value of variables on the screen. This is usually done using the echo or print statement.

Example using echo

<?php
$name = "Ali";
echo $name;
?>

Output:

Ali

Combining Text and Variables

In php Creating Variables and Displaying Them, variables are often combined with text to create meaningful output.

<?php
$age = 25;
echo "I am $age years old.";
?>

Output:

I am 25 years old.

Variables with Different Data Types

PHP supports different data types such as strings, integers, and floats. Understanding this is essential in php Creating Variables and Displaying Them.

<?php
$city = "Tehran"; // String
$population = 9000000; // Integer
$temperature = 23.5; // Float
echo “City: $city <br>”;
echo “Population: $population <br>”;
echo “Temperature: $temperature °C”;
?>

Why Variables Are Important

In php Creating Variables and Displaying Them, variables allow you to:

  • Store user input

  • Reuse values multiple times

  • Make your code cleaner and more readable

Without variables, you would need to repeat values manually, which is inefficient and error-prone.

Requirements and Setup (XAMPP / Local Server)

(php Creating Variables and Displaying Them)

Before starting php Creating Variables and Displaying Them, you need to prepare a proper development environment. PHP is a server-side language, which means it cannot run directly in a browser without a server. For this reason, we use a local server environment such as XAMPP.

What You Need for php Creating Variables and Displaying Them

To practice php Creating Variables and Displaying Them, make sure you have the following:

  1. A computer (Windows, macOS, or Linux)

  2. A web browser (Chrome, Firefox, Edge, etc.)

  3. A local server package (XAMPP recommended)

  4. A text editor (VS Code, Notepad++, or similar)

What Is XAMPP?

XAMPP is a free and popular local server package that includes:

  • Apache (Web Server)

  • MySQL (Database)

  • PHP (Programming Language)

Using XAMPP allows you to run PHP files locally, which is essential for php Creating Variables and Displaying Them.

Installing XAMPP

  1. Download XAMPP from the official website

  2. Run the installer and follow the steps

  3. After installation, open the XAMPP Control Panel

  4. Start Apache

When Apache is running, your local server is ready for php Creating Variables and Displaying Them.

Creating Your First PHP File

To begin php Creating Variables and Displaying Them, follow these steps:

  1. Go to the htdocs folder inside the XAMPP installation directory

    C:\xampp\htdocs\
  2. Create a new folder (for example: php-basics)

  3. Inside that folder, create a file named:

    index.php

Writing a Simple PHP Example

Now let’s write a simple example related to php Creating Variables and Displaying Them:

<?php
$message = "Welcome to PHP!";
echo $message;
?>

Save the file and open your browser. Type the following address:

http://localhost/php-basics/

Output:

Welcome to PHP!

This confirms that your setup is working correctly for php Creating Variables and Displaying Them.

Why Setup Is Important

Without proper setup:

  • PHP code will not execute

  • Variables will not display

  • You cannot practice php Creating Variables and Displaying Them

A correct local server environment ensures that all PHP features work as expected.

PHP Syntax Basics

(php Creating Variables and Displaying Them)

To successfully learn php Creating Variables and Displaying Them, it is essential to understand the basic syntax of PHP. PHP syntax defines how PHP code is written and how the server understands and executes it.

PHP Tags

In php Creating Variables and Displaying Them, all PHP code must be written inside PHP tags. These tags tell the server where PHP code starts and ends.

<?php
// PHP code goes here
?>

Anything outside these tags is treated as normal HTML and will be displayed directly in the browser.

PHP Statements and Semicolons

In php Creating Variables and Displaying Them, each PHP instruction is called a statement, and every statement must end with a semicolon (;).

<?php
echo "Hello PHP";
?>

If you forget the semicolon, PHP will generate an error.

Case Sensitivity in PHP

When learning php Creating Variables and Displaying Them, remember:

  • PHP keywords like echo, if, else are not case-sensitive

  • Variable names are case-sensitive

Example:

<?php
$name = "Sara";
echo $name; // Correct
// echo $Name; // This will cause an error
?>

Comments in PHP

Comments are very useful in php Creating Variables and Displaying Them because they help explain your code. PHP supports single-line and multi-line comments.

<?php
// This is a single-line comment

/*
This is a
multi-line comment
*/

?>

Comments are ignored by the server and not shown in the browser.

Mixing PHP with HTML

One important feature of php Creating Variables and Displaying Them is the ability to mix PHP with HTML easily.

<!DOCTYPE html>
<html>
<body>

<?php
$message = “Hello from PHP!”;
echo “<h1>$message</h1>”;
?>

</body>
</html>

Output:
The message will appear as a heading on the web page.

Whitespace and Line Breaks

In php Creating Variables and Displaying Them, PHP ignores extra spaces and line breaks, making your code easier to read without affecting execution.

<?php
$number = 10;

echo $number;
?>

Declaring Variables in PHP

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, declaring variables is one of the first and most important steps. A variable declaration means creating a variable and assigning a value to it so that PHP can store and use that data during script execution.

How to Declare Variables in PHP

In php Creating Variables and Displaying Them, a PHP variable:

  • Always starts with a dollar sign ($)

  • Is followed by the variable name

  • Uses the equals sign (=) to assign a value

  • Ends with a semicolon (;)

Basic Variable Declaration Syntax

$variableName = value;

Simple Examples of Declaring Variables

Here is a basic example related to php Creating Variables and Displaying Them:

<?php
$name = "Ali";
?>

In this example:

  • $name is the variable

  • "Ali" is a string value stored in the variable

Declaring Variables with Different Data Types

In php Creating Variables and Displaying Them, PHP automatically detects the data type based on the value assigned.

String Variable

<?php
$city = "Tehran";
?>

Integer Variable

<?php
$age = 30;
?>

Float Variable

<?php
$price = 19.99;
?>

Boolean Variable

<?php
$isStudent = true;
?>

PHP does not require you to define the data type explicitly, which makes php Creating Variables and Displaying Them easier for beginners.

Declaring Multiple Variables

In php Creating Variables and Displaying Them, you can declare multiple variables separately in the same script.

<?php
$firstName = "Sara";
$lastName = "Ahmadi";
$score = 95;
?>

Each variable stores its own value and can be used independently.

Displaying Declared Variables

Declaring variables is usually followed by displaying them, which is a key part of php Creating Variables and Displaying Them.

<?php
$language = "PHP";
echo $language;
?>

Output:

PHP

Important Rules for Declaring Variables

When working with php Creating Variables and Displaying Them, remember:

  • Variable names must start with a letter or underscore

  • They cannot start with a number

  • Variable names are case-sensitive

  • Avoid using spaces in variable names

❌ Invalid:

$1name = "Ali";

✅ Valid:

$_name = "Ali";

Rules for Naming Variables

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, using correct and meaningful variable names is very important. Proper naming rules help prevent errors and make your code easier to read, understand, and maintain.

Basic Rules for Naming Variables in PHP

When working with php Creating Variables and Displaying Them, PHP enforces the following rules for variable names:

  1. A variable must start with a dollar sign ($)

  2. The first character after $ must be a letter (a–z, A–Z) or an underscore (_)

  3. A variable cannot start with a number

  4. Variable names can contain letters, numbers, and underscores

  5. Variable names are case-sensitive

  6. Variable names cannot contain spaces or special characters

Valid Variable Name Examples

Here are some valid examples used in php Creating Variables and Displaying Them:

<?php
$name = "Ali";
$_age = 25;
$userName = "Sara";
$total_score = 90;
?>

All these variables follow PHP naming rules and can be safely used and displayed.

Invalid Variable Name Examples

The following examples will cause errors in php Creating Variables and Displaying Them:

<?php
$1name = "Ali"; // Cannot start with a number
$user-name = "Ali"; // Hyphen is not allowed
$full name = "Ali"; // Spaces are not allowed
?>

These variable names break PHP rules and should be avoided.

Case Sensitivity in Variable Names

In php Creating Variables and Displaying Them, variable names are case-sensitive. This means $Name and $name are treated as two different variables.

<?php
$Name = "Ali";
echo $Name; // Works

// echo $name; // Error: Undefined variable
?>

Always be consistent with variable naming to avoid confusion.

Best Practices for Variable Naming

To write clean code in php Creating Variables and Displaying Them, follow these best practices:

  • Use descriptive names that explain the variable’s purpose

  • Use camelCase or snake_case for readability

  • Avoid very short or unclear names like $x or $a

Example of Good Naming

<?php
$userEmail = "user@example.com";
echo $userEmail;
?>

Common Data Types in PHP

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, understanding data types is essential because they define what kind of data a variable can store. PHP automatically assigns a data type to a variable based on the value you give it. The most common data types you will use are String, Integer, Float, and Boolean.

String Data Type

A string is a sequence of characters used to store text. In php Creating Variables and Displaying Them, strings are written inside single (' ') or double (" ") quotes.

Example (String)

<?php
$name = "Ali";
echo $name;
?>

Output:

Ali

You can also combine strings with text:

<?php
$language = "PHP";
echo "I am learning $language.";
?>

Output:

I am learning PHP.

Integer Data Type

An integer is a whole number without decimals. In php Creating Variables and Displaying Them, integers are commonly used for counting, age, quantity, or IDs.

Example (Integer)

<?php
$age = 25;
echo $age;
?>

Output:

25

Float Data Type

A float (or double) is a number with decimal points. In php Creating Variables and Displaying Them, floats are often used for prices, measurements, or averages.

Example (Float)

<?php
$price = 19.99;
echo $price;
?>

Output:

19.99

Boolean Data Type

A boolean represents two possible values: true or false. In php Creating Variables and Displaying Them, booleans are commonly used in conditions and decision-making.

Example (Boolean)

<?php
$isLoggedIn = true;
echo $isLoggedIn;
?>

Output:

1

Note: In PHP, true is displayed as 1, and false is displayed as nothing when using echo.

Displaying Different Data Types Together

In php Creating Variables and Displaying Them, you can display multiple variables with different data types in one output.

<?php
$name = "Sara";
$age = 22;
$score = 88.5;
$isStudent = true;

echo “Name: $name <br>”;
echo “Age: $age <br>”;
echo “Score: $score <br>”;
echo “Student: $isStudent“;
?>

Assigning Values to Variables

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, assigning values to variables means storing data inside a variable so it can be used later in the PHP script. This is one of the most basic and frequently used operations in PHP programming.

How Value Assignment Works in PHP

In php Creating Variables and Displaying Them, values are assigned using the assignment operator (=).
The value on the right side of = is stored in the variable on the left side.

Basic Syntax

$variableName = value;

Assigning Simple Values

You can assign different types of values to variables in php Creating Variables and Displaying Them.

Assigning a String

<?php
$name = "Ali";
?>

Assigning an Integer

<?php
$age = 30;
?>

Assigning a Float

<?php
$salary = 4500.75;
?>

Assigning a Boolean

<?php
$isAdmin = false;
?>

PHP automatically detects the data type based on the assigned value.

Assigning and Displaying Values Together

A common practice in php Creating Variables and Displaying Them is assigning a value and then immediately displaying it.

<?php
$city = "Tehran";
echo $city;
?>

This makes your code clear and easy to understand.

Reassigning Values to Variables

In php Creating Variables and Displaying Them, variables are dynamic, which means you can change their values at any time.

<?php
$score = 70;
echo $score;

$score = 90;
echo “<br>” . $score;
?>

Output:

70
90

The new value replaces the old one.

Assigning Values Using Expressions

You can also assign values using calculations in php Creating Variables and Displaying Them.

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

echo $result;
?>

Output:

15

Assigning One Variable’s Value to Another

In php Creating Variables and Displaying Them, a variable can receive the value of another variable.

<?php
$x = 100;
$y = $x;

echo $y;
?>

Displaying Variables Using echo

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, the echo statement is the most common and simplest way to display variables and text in PHP. It outputs data directly to the browser, allowing you to see the values stored in variables.

What Is echo?

echo is a language construct in PHP used to send output to the screen. It is fast, easy to use, and does not require parentheses.

echo "Hello World";

Displaying a Variable with echo

In php Creating Variables and Displaying Them, you can display the value of a variable by writing its name after echo.

<?php
$name = "Ali";
echo $name;
?>

Output:

Ali

Displaying Text and Variables Together

A very important part of php Creating Variables and Displaying Them is combining text with variables.

Using Double Quotes

<?php
$age = 25;
echo "I am $age years old.";
?>

Output:

I am 25 years old.

Note: Variables are parsed inside double quotes.

Using Concatenation (.)

You can also use the dot (.) operator to join text and variables.

<?php
$city = "Tehran";
echo "I live in " . $city;
?>

Output:

I live in Tehran

This method is useful when working with single quotes or more complex expressions.

Displaying Multiple Variables

In php Creating Variables and Displaying Them, echo can output multiple values at once.

<?php
$firstName = "Sara";
$lastName = "Ahmadi";

echo $firstName . ” “ . $lastName;
?>

Using HTML with echo

A powerful feature of php Creating Variables and Displaying Them is displaying variables inside HTML tags.

<?php
$message = "Welcome to PHP!";
echo "<h2>$message</h2>";
?>

This will display the message as a heading on the web page.

Displaying Line Breaks

To create new lines in php Creating Variables and Displaying Them, you can use HTML line breaks.

<?php
echo "Line one<br>";
echo "Line two";
?>

Displaying Variables Using print

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, the print statement is another way to display the value of variables. It is very similar to echo, but there are some subtle differences that are good to understand.

What Is print?

print is a language construct in PHP used to display text or variables on the screen. Unlike echo, print always returns a value of 1, which allows it to be used in expressions.

Syntax:

print "Hello World";

Displaying a Variable with print

In php Creating Variables and Displaying Them, you can display a variable by passing its name to print.

<?php
$name = "Ali";
print $name;
?>

Output:

Ali

Displaying Text and Variables Together

print can also be used to combine text and variables, but unlike echo, it only accepts one argument at a time, so concatenation is often required.

<?php
$age = 25;
print "I am " . $age . " years old.";
?>

Output:

I am 25 years old.

Using print with HTML

In php Creating Variables and Displaying Them, print can display HTML tags along with variables.

<?php
$message = "Welcome to PHP!";
print "<h2>$message</h2>";
?>

This will display the message as a heading in the browser.

Differences Between echo and print

For php Creating Variables and Displaying Them:

  • echo can take multiple arguments separated by commas; print can take only one argument

  • print returns 1, while echo does not return a value

  • Otherwise, they behave similarly and can both display variables effectively

 

 

 

Combining Text and Variables

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, one of the most common tasks is combining text with variables to create meaningful output. This allows you to show dynamic information in a readable format, like user names, ages, or messages.

Using Double Quotes

In php Creating Variables and Displaying Them, variables can be directly placed inside double-quoted strings, and PHP will automatically replace them with their values.

Example:

<?php
$name = "Sara";
$age = 22;

echo “My name is $name and I am $age years old.”;
?>

Output:

My name is Sara and I am 22 years old.

Tip: Variable parsing works only in double quotes, not in single quotes.

Using Concatenation (. Operator)

Another way to combine text and variables in php Creating Variables and Displaying Them is using the dot (.) operator. This is useful for single quotes or more complex expressions.

Example:

<?php
$city = "Tehran";
$country = "Iran";

echo “I live in “ . $city . “, “ . $country . “.”;
?>

Output:

I live in Tehran, Iran.

Mixing Variables with HTML

In php Creating Variables and Displaying Them, you can also embed variables into HTML tags to produce styled content.

Example:

<?php
$message = "Welcome to PHP!";
echo "<h1>$message</h1>";
?>

Output:
The message appears as a heading on the webpage.

Best Practices

When combining text and variables in php Creating Variables and Displaying Them:

  • Use double quotes for simplicity with variables

  • Use concatenation for more complex expressions

  • Keep your variable names clear for readability

  • Always test output to ensure variables display correctly

 

 

 

 

Using HTML with PHP Variables

(php Creating Variables and Displaying Them)

In php Creating Variables and Displaying Them, one of the most powerful features is the ability to embed PHP variables inside HTML. This allows you to create dynamic web pages where content changes based on the values stored in your variables.

Basic Example

You can insert PHP variables directly into HTML by using the <?php ?> tags.

<?php
$name = "Ali";
$age = 25;
?>

<!DOCTYPE html>
<html>
<body>
<h1>Welcome, <?php echo $name; ?>!</h1>
<p>You are <?php echo $age; ?> years old.</p>
</body>
</html>

Output in Browser:

Welcome, Ali!
You are 25 years old.

Using Variables Inside HTML Tags

In php Creating Variables and Displaying Them, PHP variables can also be used in HTML attributes like class, id, src, and href.

Example:

<?php
$imageFile = "avatar.png";
$altText = "User Avatar";
?>

<img src=“<?php echo $imageFile; ?>” alt=“<?php echo $altText; ?>”>

This dynamically sets the image source and alt text using PHP variables.

Embedding Multiple Variables

You can combine multiple PHP variables with HTML content to make pages fully dynamic.

<?php
$firstName = "Sara";
$lastName = "Ahmadi";
$city = "Tehran";
?>

<p>Hello, <?php echo $firstName . ” “ . $lastName; ?> from <?php echo $city; ?>!</p>

Output:

Hello, Sara Ahmadi from Tehran!

Using Short Echo Tag

For php Creating Variables and Displaying Them, PHP also provides a shorthand <?= ?> for echo, which makes embedding variables in HTML cleaner.

<p>Hello, <?= $firstName ?>!</p>

This is equivalent to:

<p>Hello, <?php echo $firstName; ?>!</p>

Practical Examples and Exercises

(php Creating Variables and Displaying Them)

To truly understand php Creating Variables and Displaying Them, it is important to practice with real examples and exercises. Hands-on exercises help you solidify concepts like declaring variables, assigning values, combining text, and displaying output.

Example 1: Simple Variable Display

Task: Create a variable to store your name and display it.

<?php
$name = "Ali";
echo "Hello, my name is $name.";
?>

Output:

Hello, my name is Ali.

This exercise demonstrates the basics of php Creating Variables and Displaying Them.

Example 2: Combining Multiple Variables

Task: Create variables for first name, last name, and age. Display a sentence combining all.

<?php
$firstName = "Sara";
$lastName = "Ahmadi";
$age = 22;

echo “My name is $firstName $lastName and I am $age years old.”;
?>

Output:

My name is Sara Ahmadi and I am 22 years old.

This shows how php Creating Variables and Displaying Them can combine multiple variables with text.

Example 3: Using Variables in HTML

Task: Display user information inside HTML tags.

<?php
$name = "Reza";
$city = "Tehran";
?>

<h1>Welcome, <?php echo $name; ?>!</h1>
<p>City: <?php echo $city; ?></p>

Output in Browser:

Welcome, Reza!
City: Tehran

This exercise demonstrates how php Creating Variables and Displaying Them works with HTML to create dynamic web pages.

Example 4: Arithmetic with Variables

Task: Store numbers in variables, calculate total, and display.

<?php
$price1 = 50;
$price2 = 30;
$total = $price1 + $price2;

echo “The total price is $total.”;
?>

Output:

The total price is 80.

This example shows that php Creating Variables and Displaying Them is not limited to text—it can also handle calculations.

Exercise Ideas

To practice php Creating Variables and Displaying Them, try these:

  1. Create a variable for your favorite color and display a sentence:
    "My favorite color is ___."

  2. Store your birth year in a variable and calculate your age. Display the result.

  3. Create variables for a product name, quantity, and price. Calculate total cost and display it with a sentence.

  4. Create variables for a blog post title and content. Display them inside HTML <h2> and <p> tags.