PHP Variables

A quick demonstration of how to code PHP variables.

Variables are named "containers" that allow you to store a value. This value can then be used by other parts of the application, simply by referring to the variable's name. For example, the application could display the contents of the variable to the user.

In PHP, variable names must start with a dollar sign ($). For example:

Another Example

PHP variables can contain strings (like the previous example), numbers, and arrays. When a variable contains a number, you can perform calculations against that value. Here's a simple calculation using variables:

The above code results in the following:

11

Concatenation

When outputting multiple variables and other text to the screen, you can concatenate them (join them together) either with multiple echo statements, or by using one echo statement with a dot (.) between each part.

Here's an example of both methods:

Option 1

Option 2 (less code)

Both of the above code examples result in:

2 + 9 = 11

Variable Names

When creating names for your variables, you need to ensure they comply with the following naming rules: