CodeBlanks Logo Icon CodeBlanks

Variable naming rules

PHP course · Beginner · Lesson 8/116

Learn the letter, digit and underscore rules for variable names and case sensitivity.

What should a variable name look like?

In PHP, variable names must follow a few principles. After the $ sign, the name must start with a letter or an underscore; it cannot start with a digit.

The rest can be letters, digits or underscores. Spaces, hyphens and special characters are not allowed.

Examples: $userName, $_count, $city2 are valid; $1name, $first name, $first-name are invalid.

We will look at case sensitivity in the next card; for now, keep your names short and meaningful.

Case sensitivity

PHP variable names are case-sensitive. So $name, $Name and $NAME are three different variables.

Example: if you write $name = "Alex"; and $Name = "Sam";, then echo $name; prints Alex and echo $Name; prints Sam.

This is why writing names consistently matters; starting with a lowercase letter and keeping the same form is a common choice.

To avoid mistakes, always use the same letter case for the same variable.

Exercise Print three variables on separate lines

Assign "Alex" to $firstName, "Smith" to $lastName, and 25 to $age. Print the three variables on three lines with echo; end each line with \n.

Show example solution
echo $firstName; echo "\n"; echo $lastName; echo "\n"; echo $age; echo "\n";.
Example solution:
<?php
$firstName = "Alex";
$lastName = "Smith";
$age = 25;
echo $firstName;
echo "\n";
echo $lastName;
echo "\n";
echo $age;
echo "\n";

Test yourself

  1. Which is a valid variable name?

    • $1name
    • $first name
    • $first_name
    • $first-name
    Show answer

    $first_name — Correct! $first_name is valid; it has letters, an underscore and digits.

  2. Write the valid variable name

    $____ = 42;
    Show answer
    $user_age = 42;
  3. What does $Name = "Alex"; $name = "Sam"; echo $name; print?

    $Name = "Alex";
    $name = "Sam";
    echo $name;
    • Yes, they are the same variable; output is Alex.
    • No; they are different, output is Sam.
    • Yes, they are the same variable; output is empty.
    • No; they are different, output is Alex.
    Show answer

    No; they are different, output is Sam. — Correct! PHP is case-sensitive; $name prints Sam, its last value.

All lessons in Beginner