Variables and Operators

Main | Static vs. Dynamic Websites | Using PHP | A Simple PHP Program | Variables and Operators | Practice 1 | Solution 1 | Loops | Practice 2 | Solution 2 | Functions | Practice 3 | Solution 3 | Conditionals | Practice 4 | Solution 4

Variables

Variables (as taught in Algebra) can take on unknown values and allow us (and our PHP programs) to generalize, which in turn can allow for flexibility. We use variables in spoken languages like English often. For example, a common word such as age can be considered a variable because age can take different values for different people or for the same person at different times. Similarly, country can be considered a variable because a person's country can be assigned a value. Programming languages like PHP also allow us to give a name to something which we can specify in the future.

Variables are denoted in PHP by preeding them with a dollar sign ($). So if I wanted to create a variable called a, I would type the following:

$a;

When programming you should give your variables meaningful names. For example, $age will make more sense to you then $a, if you want a variable to represent someone's age. Variables should be single words (as specified at the end of our previous discussion). For example, if we were to type:

$erins age

To represent a person named Erin's age we would have a syntax error, because the word "age" would have no meaning in PHP and $erins would be the variable that we created. You should avoid having a space or a comma in your variable. It is conventional in PHP to use an underscore to take the place of space in order to keep a string a word. So, we would represent the variable for Erin's age in PHP like this:

$erins_age

Another convention which comes from Java for representing spaces is to remove all spaces, but use a capital letter to denote what you would intend to be a separate word. For example:

$erinsAge

This method is referred to by some programmers as "studly caps". In this tutorial we will be using the underscore replacement of space instead.

Operators

Operators do things to variables. If I wanted to say "my age is 26", the word "is" could be seen as an operator. The string "my age" could be seen as a variable, and "26" could be seen as the value of the variable. In PHP this would look like this:

$my_age = 26;

Note the use of the assignment operator (=) which sets $my_age to the value of 26.

PHP has other operators and you should already be familiar with most of the following:

ExampleNameResult
$a + $bAdditionSum of $a and $b.
$a - $bSubtractionDifference of $a and $b.
$a * $bMultiplicationProduct of $a and $b.
$a / $bDivisionQuotient of $a and $b.
$a % $bModulusRemainder of $a divided by $b.

Throughout the tutorial we will learn about new operators, but in our next example we will learn about special variables.


jfulton [at] member.fsf.org
22 Aug 2013