Learn

Short lessons with real code you can edit and run on the page.

Variables in PHP

Lesson 3 PHP 8.5 Runs in your browser
In short

You create a PHP variable by writing a dollar sign, a name, an equals sign and a value. The statement $name = "Ada"; creates $name and stores the text Ada in it, with no keyword or type. For a value that never changes, define a constant with const or define(), written without a $.

Key facts

  • $color and $Color are two separate variables, because PHP variable names are case-sensitive.
  • A variable name can't start with a digit, so $2nd_user = "Ada"; stops PHP with a parse error.
  • Reading a variable before it has a value triggers Warning: Undefined variable, and the script keeps running.
  • Only define() works inside an if block or a function. A const line there is a parse error.
  • Defining the same constant twice keeps the first value. Since PHP 8.5, the warning adds that this will be an error in PHP 9.

How do you create a variable in PHP?

Assign a value to a name that starts with a dollar sign. The variable exists from that statement on, and PHP needs no keyword or type in front of the name.

PHP
<?php
$name = "Ada";
$age = 36;
echo $name, "\n";
echo $age, "\n";
Output
Ada
36

The = sign is the assignment operator, and it doesn't mean "equals" here. It stores the value on its right in the variable on its left. Read $age = 36; as "$age gets set to 36".

The comma in each echo line lets one statement print several values, here the variable and then the line break "\n".

Inside double quotes, PHP also replaces a variable's name with its value, so echo "Hi, $name"; prints Hi, Ada.

What happens when you read a PHP variable before it has a value?

PHP issues a warning that the variable is undefined and carries on with the script. Until the assignment runs, the variable counts as null, and echo prints nothing for it.

PHP
<?php
echo $total, "\n";
$total = 5;
echo $total, "\n";
Output

Warning: Undefined variable $total in /app/main.php on line 2

5

PHP starts each warning with a line break of its own, which makes the first blank line. The first echo then prints nothing for $total, and its line break leaves the blank line before 5.

A warning doesn't stop the script the way a parse error does. A misspelled name therefore lets the rest of the code run with an empty value.

What are the rules for variable names in PHP?

After the $, a name starts with a letter or an underscore, followed by letters, digits or underscores. The five points below sum up PHP's naming rules.

  • The first character is a letter or an underscore. $Title, $_count and $user_name work, but $2nd_user stops PHP with a parse error.
  • Spaces and hyphens can't appear in a name. Join words with an underscore or a capital letter instead, as in $first_name or $firstName.
  • Accented and non-Latin letters count as letters. That makes $café a valid name.
  • Keywords are allowed. $class and $echo are valid variable names, even though class and echo are PHP keywords.
  • $this is reserved for objects. Assigning to it, as in $this = 5;, stops PHP with a fatal error.

PHP reads $first-name as $first minus name, so the = that follows makes no sense, and PHP stops before running any of the code.

PHP
<?php
$first-name = "Ada";
Output

Parse error: syntax error, unexpected token "=" in /app/main.php on line 2

PHP doesn't enforce a naming convention. Both snake_case, as in $first_name, and camelCase, as in $firstName, are common, and sticking to one style saves you from guessing how a name was written. The case converter turns a phrase into either style, or into CONSTANT_CASE for constants.

Are PHP variable names case-sensitive?

Yes. $color and $Color are two separate variables, and each keeps its own value.

PHP
<?php
$color = "red";
$Color = "blue";
echo $color, "\n";
echo $Color, "\n";
Output
red
blue

The wrong letter case doesn't stop the script. If no variable with that exact spelling was assigned, PHP prints Warning: Undefined variable with the name you typed and goes on. Compare that name with the one you assigned.

Can you change the value of a PHP variable?

Yes. Assign a new value to the same name, and the old value is replaced.

PHP
<?php
$score = 10;
echo $score, "\n";
$score = $score + 5;
echo $score, "\n";
$score = "fifteen";
echo $score, "\n";
Output
10
15
fifteen

In $score = $score + 5;, PHP works out the right side first, using the current value of 10, and then stores the result, 15. Reassigning a variable this way is how a counter or a running total goes up.

The last assignment puts text into a variable that held a number. PHP allows that, because the type belongs to the value, not to the variable.

Does assigning one PHP variable to another link the two?

No. $sale = $price; copies the value, so a later change to one variable doesn't affect the other.

PHP
<?php
$price = 20;
$sale = $price;
$price = 25;
echo $sale, "\n";
echo $price, "\n";
Output
20
25

Changing $price to 25 leaves $sale at 20. To make two names share one value, assign by reference with an ampersand, as in $sale = &$price;. Changing either variable then changes both.

How do you define a constant in PHP?

Use the const keyword or the define() function, and leave the $ off the name.

PHP
<?php
const MAX_USERS = 100;
define("SITE_NAME", "Example Shop");
echo MAX_USERS, "\n";
echo SITE_NAME, "\n";
Output
100
Example Shop

A constant holds a value that stays the same for the whole run of the script, such as a user limit or a site name. define() takes the name as a string in quotes, but you read the constant by its bare name.

Constant names use the same characters as variable names, but const rejects keywords such as class and echo, which makes const ECHO = 1; a parse error. By convention, constant names are written in uppercase, like MAX_USERS.

Constant names are case-sensitive. If the code defines COLOR, writing Color stops PHP with an Undefined constant error. The built-in constants true, false and null are the exception and work in any letter case.

Every constant is also global, and code anywhere in the script can read it, even inside a function. Variables work differently, because a variable created outside a function usually isn't visible inside it. This rule comes from what PHP calls variable scope.

Settings that stay fixed for a whole run suit constants well. In the password reset tutorial, the config.php file keeps its database and email settings in constants such as DB_HOST, defined with define().

Should you use const or define() in PHP?

Use const at the top level of a file, outside any block or function, and define() elsewhere.

When PHP compiles the file into instructions, before running any of it, it checks where each const line sits and whether its value uses a function call or a variable. A const that fails either check stops the whole script before anything runs, while define() is checked only when PHP reaches its line.

PHP const and define() compared
constdefine()
Works only at the top level of a fileAlso works inside if blocks and functions
A misplaced const stops the script before any code runsA define() problem shows up only when PHP reaches the line
Needs the name written out in the codeCan take the name from a variable
Can't get its value from a function callCan get its value from a function call
Is a statement and returns no valueReturns true, or false and a warning if the name is taken

With const and define() alike, the constant exists only once PHP has run its line, so code that runs before that line can't use it. An if block runs the code between its braces only when its condition is true, and PHP refuses a const line inside one even when the condition is true.

PHP
<?php
if (true) {
    const MODE = "debug";
}
echo MODE, "\n";
Output

Parse error: syntax error, unexpected token "const" in /app/main.php on line 3

The same block with define() runs and creates the constant.

PHP
<?php
if (true) {
    define("MODE", "debug");
}
echo MODE, "\n";
Output
debug

Outside those cases, const is the shorter of the two, and a group of const lines at the top of a file shows every fixed value in one place.

Can you change a constant in PHP?

No. A constant keeps its first value until the script ends.

An assignment such as LIMIT = 20; is a parse error, and a second define() with the same name leaves the value alone.

PHP
<?php
define("LIMIT", 10);
define("LIMIT", 20);
echo LIMIT, "\n";
Output

Warning: Constant LIMIT already defined, this will be an error in PHP 9 in /app/main.php on line 3
10

PHP keeps 10 and prints a warning for the second define(), which also returns false. Since PHP 8.5, redefining a constant is deprecated. Deprecated code still works, but PHP warns about it and a future version may remove it. Here the warning adds that this will be an error in PHP 9.

To define a constant only when it doesn't exist yet, test the name with defined() first. It takes the name in quotes and returns true or false.

Which constants does PHP define for you?

Every PHP script can read a long list of predefined constants without defining anything.

PHP
<?php
echo PHP_MAJOR_VERSION, "\n";
echo PHP_INT_MAX, "\n";
echo __LINE__, "\n";
Output
8
9223372036854775807
4

PHP_MAJOR_VERSION holds the first number of the PHP version, 8 in both 8.5 and 8.6. PHP_INT_MAX is the largest value PHP's integer type can hold.

PHP_VERSION holds the full version as a string, such as 8.5.12 in the runner and 8.6.0 on PHP 8.6.0. Many other constants come from extensions and exist only when their extension is loaded. An extension is a part of PHP that adds features, and not every PHP setup loads the same ones.

__LINE__ is one of the magic constants, which aren't real constants despite the name. Its value is the number of the line it sits on, 4 here, and magic constants work in any letter case.

Do variables and constants work the same in PHP 8.5 and 8.6?

Variables work the same, and PHP 8.6 deprecates two things about constants made with define() or a top-level const.

The runner uses PHP 8.5.12 and prints neither deprecation notice. The two output blocks in this section come from PHP 8.6.0.

Why does a third argument to define() print a notice in PHP 8.6?

The third argument of define() used to make a constant case-insensitive, and PHP 8.6 deprecates passing it. An argument is a value passed to a function inside its parentheses. PHP 8.0 removed the ability to define case-insensitive constants, and define() has ignored the third argument ever since.

PHP
<?php
define("GREETING", "Hello", false);
echo GREETING, "\n";
Output on PHP 8.6.0
Deprecated: define(): Argument #3 ($case_insensitive) is ignored and treated as false since declaration of case-insensitive constants is no longer supported, passing the argument explicitly is unnecessary in /app/main.php on line 2
Hello

With true as the third argument, PHP 8.6.0 prints the same Deprecated line and a warning that this will be an error in PHP 9.0, while PHP 8.5 prints only a shorter warning. The constant stays case-sensitive either way, so leave the argument out.

Which constant names are deprecated in PHP 8.6?

PHP 8.6 deprecates let and is as names of constants, functions and classes, and _ as a constant name.

The deprecation keeps the words let and is free for possible future keywords, and the check ignores letter case, which means the usual uppercase spelling IS gets the notice too. Variables named $let, $is and $_ aren't affected.

PHP
<?php
const IS = true;
$is = true;
echo "Done\n";
Output on PHP 8.6.0
Deprecated: Calling a constant "is" is deprecated since 8.6 in /app/main.php on line 2
Done

PHP 8.6.0 reports the constant IS as "is" in lowercase and gives the variable $is on line 3 no notice.

PHP 8.6 makes two more changes that matter only once you use classes and objects, a later topic. It deprecates namespace as a constant name inside a class, and it lets code write new data directly into an object that a constant holds. The constant itself still holds the same object.

Common mistakes with variables in PHP

PHP's messages for variable and constant mistakes often describe the symptom. The cause is usually one step back.

  • Parse error: syntax error, unexpected token "=". The $ is missing, as in name = "Ada";, or a hyphen splits the name. Add the $, or replace the hyphen with an underscore.
  • Warning: Undefined variable $Name. The name doesn't match the one you assigned, often because of a capital letter or a typo. Copy the name from the line that assigns it.
  • Warning: Undefined variable $LIMIT. A $ in front of a constant's name makes PHP look for a variable. Write the constant without it, as LIMIT.
  • The constant's name shows up in the output. PHP doesn't look for constants inside quotes, so "Welcome to SITE" prints the word SITE. Put the constant outside the quotes.

The script below makes the last mistake on its first echo line and fixes it on the second.

PHP
<?php
define("SITE", "Example Shop");
echo "Welcome to SITE\n";
echo "Welcome to ", SITE, "\n";
Output
Welcome to SITE
Welcome to Example Shop

Exercise

Fix this script so it prints Lisbon, Portugal and then Porto, Portugal on the next line. Keep COUNTRY a constant, and change the value of $city instead of adding a second variable. Print the place names from $city and COUNTRY rather than typing them again.

PHP
<?php
const COUNTRY = "Portugal";
$city = "Lisbon";
echo $City, ", ", COUNTRY, "\n";
city = "Porto";
echo $city, ", ", $COUNTRY, "\n";
Output
Show the solution
<?php
const COUNTRY = "Portugal";
$city = "Lisbon";
echo $city, ", ", COUNTRY, "\n";
$city = "Porto";
echo $city, ", ", COUNTRY, "\n";

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this script print?

    <?php
    $message = "Hi";
    echo $Message;
  2. 2What does this script print?

    <?php
    $drink = "tea";
    $order = $drink;
    $drink = "coffee";
    echo $order;
  3. 3Which of these is a valid PHP variable name?

  4. 4Which line defines a constant correctly?

  5. 5Where can you use define() but not const?

Frequently asked questions

Do you have to declare a variable before using it in PHP?
No, PHP has no separate declaration step for variables. A variable comes into existence the first time you assign it a value, and its type follows that value. Reading it before then gives an Undefined variable warning.
Can you use var or let to create a variable in PHP?
No, a PHP variable needs no keyword in front of its name. In a script or a function, writing var $name = 'Ada'; or let $name = 'Ada'; stops PHP with a parse error. Start the line with the $ name itself.
What is the difference between a variable and a constant in PHP?
A variable can change its value, while a constant keeps its first value until the script ends. Variable names start with $ and constant names don't. Constants are also global, which lets code inside a function read them directly.
Are constant names case-sensitive in PHP?
Yes, constant names are case-sensitive in PHP 8, so GREETING and Greeting are two different names. The built-in true, false and null are exceptions that work in any letter case. Passing true as the third argument of define() no longer makes a constant case-insensitive.
What are variable variables in PHP?
A variable variable uses the value of one variable as the name of another, written with two dollar signs. After $field = 'color', the line $$field = 'blue' sets $color to blue. An array is usually the clearer way to store values under names your code builds.
Can a PHP constant hold an array?
Yes, both const and define() accept an array as the value. With const COLORS = ['red', 'green', 'blue'], the expression COLORS[1] gives green, because array positions start at 0.
How do you check whether a constant exists in PHP?
Call defined() with the constant's name in quotes, and it returns true only if that constant exists. A test such as if (!defined('TIMEOUT')) lets code define a constant only when it doesn't exist yet, which avoids the already defined warning.