Variables in PHP
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
$colorand$Colorare 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 anifblock or a function. Aconstline 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.
$name = "Ada";
$age = 36;
echo $name, "\n";
echo $age, "\n";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.
echo $total, "\n";
$total = 5;
echo $total, "\n";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,$_countand$user_namework, but$2nd_userstops 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_nameor$firstName. - Accented and non-Latin letters count as letters. That makes
$caféa valid name. - Keywords are allowed.
$classand$echoare valid variable names, even thoughclassandechoare PHP keywords. $thisis 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.
$first-name = "Ada";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.
$color = "red";
$Color = "blue";
echo $color, "\n";
echo $Color, "\n";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.
$score = 10;
echo $score, "\n";
$score = $score + 5;
echo $score, "\n";
$score = "fifteen";
echo $score, "\n";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.
$price = 20;
$sale = $price;
$price = 25;
echo $sale, "\n";
echo $price, "\n";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.
const MAX_USERS = 100;
define("SITE_NAME", "Example Shop");
echo MAX_USERS, "\n";
echo SITE_NAME, "\n";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.
const | define() |
|---|---|
| Works only at the top level of a file | Also works inside if blocks and functions |
A misplaced const stops the script before any code runs | A define() problem shows up only when PHP reaches the line |
| Needs the name written out in the code | Can take the name from a variable |
| Can't get its value from a function call | Can get its value from a function call |
| Is a statement and returns no value | Returns 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.
if (true) {
const MODE = "debug";
}
echo MODE, "\n";Parse error: syntax error, unexpected token "const" in /app/main.php on line 3
The same block with define() runs and creates the constant.
if (true) {
define("MODE", "debug");
}
echo MODE, "\n";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.
define("LIMIT", 10);
define("LIMIT", 20);
echo LIMIT, "\n";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.
echo PHP_MAJOR_VERSION, "\n";
echo PHP_INT_MAX, "\n";
echo __LINE__, "\n";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
define("GREETING", "Hello", false);
echo GREETING, "\n";
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
const IS = true;
$is = true;
echo "Done\n";
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 inname = "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, asLIMIT. - 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.
define("SITE", "Example Shop");
echo "Welcome to SITE\n";
echo "Welcome to ", SITE, "\n";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.
const COUNTRY = "Portugal";
$city = "Lisbon";
echo $City, ", ", COUNTRY, "\n";
city = "Porto";
echo $city, ", ", $COUNTRY, "\n";
Lisbon, Portugal Porto, Portugal
Show the solution
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.
-
1What does this script print?
$message = "Hi"; echo $Message;Variable names are case-sensitive, so $Message is a separate variable that was never assigned. The text Hi belongs to $message with a lowercase m, and PHP never treats the two names as one.
-
2What does this script print?
$drink = "tea"; $order = $drink; $drink = "coffee"; echo $order;The line $order = $drink; copies the value tea into $order. Giving $drink a new value afterward leaves the copy alone. Coffee would appear only if the two were linked by reference with &.
-
3Which of these is a valid PHP variable name?
After the $, a name starts with a letter or an underscore and holds only letters, digits and underscores. $user-name looks close, but PHP reads the hyphen as a minus sign, so $user-name = 1; stops with a parse error.
-
4Which line defines a constant correctly?
A constant name takes no $, and it needs const or define() in front of it. In define(RATE, 0.2) the name is missing its quotes, so PHP looks for an existing constant called RATE and stops with an Undefined constant error.
-
5Where can you use define() but not const?
PHP accepts const only at the top level of a file, outside blocks and functions, while define() works wherever its line runs. A string value works with both, as const COLOR = 'red'; shows.























