A variable is a special container that you can define to "hold" a value. Variables are fundamental to programming. Without variables, we would be forced to hard-code all the values in our scripts. By adding two numbers together and printing the result, you can achieve something useful:
print (2 + 4);
This script will only be useful for people who want to know the sum of 2 and 4, however. To get past this, you could write a script for finding the sum of another set of numbers, say 3 and 5. However, this approach to programming is clearly absurd, and this is where variables come into play.
Variables allow us to create templates for operations (adding two numbers, for example), without worrying about what values the variables contain. Values will be given to the variables when the script is run, possibly through user input, or through a database query.
You should use a variable whenever the data that you are subjecting to an operation in your script is liable to change from one script execution to another, or even within the lifetime of the script itself.
A variable consists of a name of your choosing, preceded by a dollar sign ($). Variable names can include letters, numbers, and the underscore character (_). They cannot include spaces. They must begin with a letter or an underscore. The following code defines some legal variables:
$a; $a_longish_variable_name; $2453; $sleepyZZZZ;
Your variable names should be meaningful as well as consistent in style. For example, if your script deals with name and password values, don't create a variable called $n for the name and $p for the password?those are not meaningful names. If you pick up that script weeks later, you might think that $n is the variable for "number" rather than "name" and that $p stands for "page" rather than "password."
A semicolon (;)?also known as the instruction terminator?is used to end a PHP statement. The semicolons in the previous fragment of code are not part of the variable names.
A variable is a holder for a type of data. It can hold numbers, strings of characters, objects, arrays, or Booleans. The contents of a variable can be changed at any time.
As you can see, you have plenty of choices when naming variables. To declare a variable, you need only include it in your script. When you declare a variable, you usually assign a value to it in the same statement, as shown here:
$num1 = 8; $num2 = 23;
The preceding lines declare two variables, using the assignment operator (=) to give them values. You will learn about assignment in more detail in the "Operators and Expressions" section later in this hour. After you give your variables values, you can treat them exactly as if they were the values themselves. In other words
is equivalent to
as long as $num1 contains 8.