Skip to main content

Creating (Declaring) PHP Variables

PHP variables are easy to spot because each name begins with a $ sign. There is no separate declaration step: the variable comes into existence when you first give it a value.

Create variables

$txt receives a string and $x an integer, and echo prints each of them:

Prompt
Write a PHP script that creates a string variable $txt with the value "Hello World!" and an integer variable $x with the value 5, then uses echo to output each variable on its own line.
Output: PHP script

PHP Variables

Names can be as short as $x and $y, or they can describe the contents, as in $age, $carname and $total_volume.

When choosing a name, follow these rules:

  • Write a $ sign first, with the name right after it.
  • Begin the name with a letter or an underscore.
  • Never begin the name with a number.
  • Use only letters, digits and underscores (A-z, 0-9, and _).
  • Watch the case, because $age and $AGE are separate variables.

Output Variables

To show something on the screen, PHP code often uses the echo statement. It can print plain text, the contents of a variable, or both.

Output a string and a variable

The text and the variable are joined with a dot, and echo prints the whole sentence:

Prompt
Write a PHP script that creates a variable $txt with the value "PromptCookbook" and uses echo to output "I love " followed by the variable.
Output: PHP script

Sum of two variables

echo can print the result of a calculation too, such as adding two variables:

Prompt
Write a PHP script that creates two integer variables $x with value 5 and $y with value 4, then uses echo to output the sum of $x + $y.
Output: PHP script

PHP is a Loosely Typed Language

You may have noticed that none of these examples states a data type. PHP works it out from the value and attaches it to the variable for you. Because the rules are this relaxed, you can even add a numeric string to an integer and get no error.

PHP 7 brought in type declarations as an option. They let you say which data type a function expects when you declare it, and if you turn on the strict requirement, a type mismatch causes a Fatal Error.