Working with Variables
In this lesson you learn what variables are, how to define them, and how to use them in several ways. You learn how PHP treats text and numbers differently.
Introduction to Variables
Variables are used to store information that can change. By creating variables, you have a way to write a program that can be used again and again with different data.
Say you want to calculate the tip at a restaurant. You normally give 20 percent. You know that to calculate a 20 percent tip you multiply the cost of the dinner by .20. You then add the tip to the cost of the dinner to get the total you pay. Your formula stays the same every time you go out to eat (well, unless the service is exceptionally bad or good, of course), but the cost of the dinner is different each time. You can think of the cost of the dinner as a variable.
In PHP, variables start with a dollar sign and you assign the variable a value using the = sign:
$costOfDinner = 15.95;
The following list includes rules for naming variables (after the $):
- You must start variables with a letter or an underscore. By convention, underscores are used only at certain times. You learn about when to use underscores in Lesson 15. For now, always start with a letter.
- You can use only alphanumeric characters and underscores (a–z, A–Z, 0–9 and _).
- You cannot use dashes or spaces.
- If the variable is more than one word, you should separate the words with capitalization or underscores.
PHP is case sensitive, ...