1. PHP Variables
Variables are PHP's method of storing values, or information. Once a variable is set, it can be used over and over again, saving you the work of typing in the value again and again, and allowing you to assign new values spontaneously.
Variables are identified by a dollar sign, immediately followed by a variable name. Variable names are case-sensitive, but you can name your own variables as long as they abide by four basic rules:
1. Variable names cannot contain spaces.
2. Variables names can contain letters (a-z and A-Z), numbers (0-9) and underscores (_).
3. Variable names can begin with letters or an underscore, but cannot begin with numbers.
4. Variable names should make sense so that you can remember them later!
Several examples of variables being assigned are below:
$NonSensical_Variable_Name = "I am a variable value.";
$empty_variable = "";
$eyes = "brown";
$hair = 'brown';
$age = 35;
?>
As you can see, value is assigned to a variable using the "equal to" symbol, after which the value is declared. Numerical values do not require single or double quotes, but strings do in order to identify the beginning and end of each string.
Most programming languages make you declare the data type of each variable that you set, but PHP automatically decides the data type of each variable for you, saving you the trouble of declaring each one. Any value set using single or double quotes will be a string, including numerical values. Numerical values set without using single or double quotes will be integers, which can be used to perform mathematical calculations, etc. There are eight different data types, including strings and integers, most of which we will learn more about later on.
If the whole point (why variables?!) is still fuzzy, don't worry, it will clear up quickly as we progress. In the meantime, don't forget to terminate each variable declaration with the ever-trusty semicolon!
2. The Echo Statement
PHP gives two options to choose between in order to output text to the browser. Although the two options are similar, "echo" is used far more than "print" because it is generally faster, shorter to type, and sounds cool! For the examples in this tutorial we will be using echo exclusively, so let's learn all about it.
$numbers = 123;
echo "Why did the lizard go on a diet?";
echo 'It weighed too much for its scales!';
echo $numbers;
?>
Echo accepts both variables and strings (in single or double quotes). Variables can be "echoed" by themselves, or from inside of a double-quoted string, but putting variable names inside a single-quoted string will only output the variable name. For example:
$numbers = 123;
echo "There are only 10 numbers. These numbers are: $numbers";
echo 'There are only 10 numbers. These numbers are: $numbers';
?>
The example above will result in:
There are only 10 numbers. These numbers are: $numbers
HTML elements can be echoed as part of a string or variable, but they will be interpreted by the browser instead of being displayed as part of the string or variable. This brings up an interesting point, because when double quotes are used to begin and end a string, using double quotes inside of the string will cause errors. The same applies to single quotes. The following examples will cause errors:
echo "<p style="color: green;"></p>";
echo 'What's this? An error message?';
?>
There are two ways to fix this problem (besides the obvious "don't use quotes inside your string"). One way is to use only double quotes inside of single quotes, and to use only single quotes inside of double quotes. The better way is to "escape" each quote that would create a problem.. The escape character is a backslash \. The following examples will not cause errors:
echo '<p style="color: green;"></p>';
echo "<p style=\"color: green;\"></p>";
echo "What's this? No error message?";
echo 'What\'s this? No error message?';
?>
These rules, since they apply to strings, work the same with variables as they do with the echo statement. On the next page we will learn more about these suspicious stringy thingys.
3. PHP Strings
Strings are lines of symbols or characters, such as words or phrases. They can be stored in variables, sent directly to the browser using the echo statement, or used in various functions. Strings do not have a size/length limit.
As we have already learned, strings begin and end with either single quotes or double quotes. Variables are understood to be variables when they are placed inside double-quoted strings, but variables are nothing more than additional text when placed inside single-quoted strings.
String Escape Characters
What happens when there are single quotes inside a single-quoted string, double quotes inside a double-quoted string, or you actually want the dollar sign to be a part of your string instead of referencing a variable? The backslash is used to escape characters such as these in double-quoted strings. The only character inside a single-quoted string that will require escaping is a single quote (apostrophe).
Character | Meaning |
\' | Escapes A Single Quote In A Single-Quoted String |
\" | Escapes A Double Quote In A Double-Quoted String |
\$ | Escapes A Dollar Sign In A Double-Quoted String |
\\ | Escapes A Backslash In A Double-Quoted String |
\n | Creates A New Line, Not In HTML, But In Files, Etc |
Examples:
$string = 'This string\'s extra apostrophe is escaped.';
$string = "This \"string\" contains escaped double quotes.";
$string = "This \$0.00 string contains an escaped dollar sign.";
?>
Strings are rather straight-forward once you get the hang of them, so let's move on to some methods of manipulating strings.
String Concatenation (The "Dot" Operator)
The word "concatenate" means "to link together, or to unite in a series or a chain". It is possible to link together a series of one or more strings using the concatenation or "dot" operator, as it is informally called. Let's look at an example first.
$variable1 = "abcdefghijklm";
$variable2 = "nopqrstuvwxyz";
$variable3 = $variable1 . $variable2;
echo $variable3;
echo $variable1 . $variable2;
?>
What we see in our example are two variables containing strings, and a third variable using the concatenation operator to combine those two variables and store the contents of them both in a new variable. When the contents of the third variable are sent to the browser, the result will be "abcdefghijklmnopqrstuvwxyz", because the concatenation operator added what was on the right (variable #2) to the end of what was on the left (variable #1).
String concatenation can be performed directly from within an echo statement as well. And, in both variables and in the echo statement, strings and variables can be interchangeably concatenated.
$variable1 = "abcdefghijklm";
$variable2 = "nopqrstuvwxyz";
echo "The letters of the alphabet are: " . $variable1 . $variable2;
?>
Can you see what the result will be?
String Concatenation Assignment
The assignment operator .= is used as a shortcut to concatenate two strings without assigning a new variable. It takes an existing variable and adds a new string onto the end (right side) of that variable's existing string.
$variable = "01234";
$variable .= "56789";
echo $variable;
?>
The result is:
Next, we will take a look at a number of functions that can manipulate strings in various ways.
4. PHP Operators
Operators perform operations. They are symbols, or combinations of symbols, that assign value, combine values or compare values, to name just a few of their uses. Without operators, PHP is pretty much useless. In fact, you have already been introduced to several operators without even realizing it!
PHP operators can be broken down into several categories, which we will now review, beginning with the operators that we have already learned.
Assignment Operators
Very simply, assignment operators assign value. We have already used the assignment operator to assign values to variables.
Operator | Description |
= | Assign a Value |
$variable = "abcde";
echo $variable; // Result: abcde
?>
String Operators
String operators, as we have learned, can either link two strings together, or add one string to the end of another string.
Operator | Description |
. | Concatenates (Links) Two Strings Together |
.= | Adds A String Onto the End of An Existing String |
$variable = "abcde" . "fghij";
$variable .= "klmno";
echo $variable; // Result: abcdefghijklmno
?>
Arithmetic Operators
Math! Some people like it and some people don't. Why not have fun writing a PHP script that does your math for you?
Operator | Description |
+ | Addition Operator (Adds Two Values Together) |
- | Subtraction Operator (Subtracts One Value From Another) |
* | Multiplication Operator (Multiplies Two Values) |
/ | Division Operator (Divides One Values From Another) |
% | Modulus Operator (Determines The Remainder of a Division) |
Arithmetic operations can be performed on variables, within variables, echoed directly, etc.
$addition = 5 + 5;
echo $addition; // Result: 10
$subtraction = 5 - 5;
echo $subtraction; // Result: 0
$multiplication = 5 * 5;
echo $multiplication; // Result: 25
$division = 5 / 5;
echo $division; // Result: 1
$modulus = 7 % 5;
echo $modulus; // Result: 2
echo 3 + 5 / 2; // Result: 5.5
?>
What?! It made sense until the last example, right? If you were expecting the results of the last example to be "4", then you might not have known about operator precedence, which states that multiplication and division come before addition and subtraction. To solve this problem you can use parenthesis to group the numbers that you want to be calculated first.
This rule is also known as PEMDAS (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction), BEDMAS (Brackets, Exponents, Division, Multiplication, Addition, Subtraction), BIDMAS (Brackets, Indices, Division, Multiplication, Addition, Subtraction) or BODMAS (Brackets, Orders, Division, Multiplication, Addition, Subtraction).
echo (3 + 5) / 2; // Result: 4
?>
Problem solved; happy calculating!
Combined Assignment Operators
Combined assignment operators are shortcuts useful when performing arithmetic operations on an existing variable's numerical value. They are similar to the concatenation assignment operator.
Operator | Description |
+= | Adds Value to An Existing Variable Value |
-= | Subtracts Value From Existing Variable Value |
*= | Multiplies An Existing Variable Value |
/= | Divides An Existing Variable Value |
%= | Modulo of An Existing Variable Value And New Value |
Example before combined assignment operator is used:
$variable = 8;
$variable = $variable + 3;
echo $variable; // Result: 11
?>
Example of combined assignment operator in use:
$variable = 8;
$variable += 3;
echo $variable; // Result: 11
?>
Incrementing/Decrementing Operators
There are shortcuts for adding (incrementing) and subtracting (decrementing) a numerical value by one.
Operator | Description |
++ | Incrementation Operator (Increases A Value By 1) |
-- | Decrementation Operator (Decreases A Value By 1) |
$variable = 15;
$variable++;
echo $variable; // Result: 16
$variable--;
echo $variable; // Result: 15
?>
Comparison Operators
Comparison operators compare two values and return either true or false, depending on the results of the comparison. They are used in conditions, which we will study in the next chapter.
Operator | Description | Example |
== | Is Equal To | 3==2 (Will Return "False") |
!= | Is Not Equal To | 3!=2 (Will Return "True") |
<> | Is Not Equal To | 3<>2 (Will Return "True") |
> | Is Greater Than | 3>2 (Will Return "True") |
< | Is Less Than | 3<2 (Will Return "False") |
>= | Is Greater Than or Equal To | 3>=2 (Will Return "True") |
<= | Is Less Than or Equal To | 3<=2 (Will Return "False") |
Logical Operators
Logical operators usually work with comparison operators to determine if more than one condition is true or false at the same time.
Operator | Meaning | Description |
&& | And | True If Two Statements Are True, Otherwise False |
|| | Or | True If One Statement or Another Is True, Otherwise False |
! | Not | True If Statement Is False, False If Statement Is True |
Logical operators make more sense when they are applied to practical examples, so let's keep moving. Next up we'll learn about conditions!