CodeBlanks Logo Icon CodeBlanks

Declaring variables

PHP course · Beginner · Lesson 7/116

Learn to declare variables with the $ sign and assign values.

What is a variable?

A variable is a box that stores a value under a name. In PHP every variable name starts with the $ sign.

To assign a value you use the = sign; it places the right-hand value into the left-hand name.

Example: $city = "Berlin"; — the variable $city now holds Berlin.

Later, echo $city; prints Berlin to the screen. Once declared, you can use the variable as many times as you like.

Print a variable with echo

After you declare a variable, you can print its value with echo.

Example: you declared $product = "Pen";. Then echo $product; prints Pen on the screen.

To print several variables on separate lines, add echo "\n"; after each one; \n means a new line.

This way you write the variable name once but reuse its value as many times as you need.

Exercise Print name and age

Assign "Alex" to $firstName and 25 to $age. Then print each on its own line with echo; end each line with \n.

Show example solution
Start with echo $firstName;, then echo "\n";, then echo $age; and echo "\n";.
Example solution:
<?php
$firstName = "Alex";
$age = 25;
echo $firstName;
echo "\n";
echo $age;
echo "\n";

Test yourself

  1. Which is a valid variable declaration?

    • $name = "Alex";
    • name = "Alex";
    • $name = Alex;
    • $$name = "Alex";
    Show answer

    $name = "Alex"; — Correct! A declaration starting with $ and assigning a quoted value is valid.

  2. Add the $ sign

    ____city = "Berlin";
    Show answer
    $city = "Berlin";
  3. Match each concept to its meaning

    $
    starts a variable name
    =
    assigns a value
    echo
    prints a value to the screen
    $city
    example variable name

All lessons in Beginner