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:
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:
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 2 (less code)
Both of the above code examples result in:
When creating names for your variables, you need to ensure they comply with the following naming rules:
- All PHP variable names must start with a letter or underscore (
- Variable names can only contain alpha-numeric characters and underscores ( i.e.
- Variable names must not contain spaces. For multi-word variable names, either separate the words with an underscore (
_) or use capitalization.