Home Tutorial PHP Lesson 06 - Operators

MSN Random Online

Lesson 06 - Operators PDF Print E-mail
Written by Administrator   
Thursday, 15 February 2007 18:07

Lesson 06 - Operators

We've already discussed two operators in our lessons up to this point.  The first one and probably the most important operator we discussed was the assignment operator ("=").  This operator allowed us to assign values to variables and arrays (which we recently learned about).  The other operator we discussed was the array operator ("=>") which allowed us to match array "keys" to array "values".  There are also the "concatenation" operators which combine strings.  Here are examples of them all:

$variable = 'name'; //assign "name" to the variable $variable using the assignment operator
echo "$variable\n"; //remember the "newline" character I taught last lesson...

$array = array('first' => 'something','second' => 'something else'); //assign array keys and values
print $array['first'] . "\n"; //print the array value with key "first"; concatenation operator used
/* there is also a lesson to be learned here, you can't print arrays inside double quotes like you would variables.
You either have to assign the specific array element to a variable and print that or use the concatenation method
which we learned in lesson 4 */

Pay particular attention to the above comments as some of them were not discussed in previous lessons.  In this lesson I'll go over some other common operators you might want to use.

The arithmetic operators are used to do simple mathematical operations such as addition, subtraction, multiplication, and division.  Here are examples of each:

$number1 = 12;
$number2 = 3;

$answer = $number1 + $number2;
echo "$answer\n"; //prints 15
$answer = $number1 - $number2;
echo "$answer\n"; //prints 9
$answer = $number1 * $number2;
echo "$answer\n"; //prints 36
$answer = $number1 / $number2;
echo "$answer\n"; //prints 4

A few other common operators you will find yourself using often are the following:

Here is a combination operator, concatenation and assignment in one.  This operator takes the original string and adds a new string onto it.

$string = 'hello'; //assign our original string
$string .= ' there'; //concatenate a new string onto it using the ".=" operator
echo "$string\n"; //prints "hello there";

Here is a combination operator, addition and assignment in one.  This operator takes the original number and adds a new number to it.

$number = 12; //assign our original number
$number += 3; //add a new number to it using the "+=" operator
echo "$number\n"; //prints "15"

That's about it for this lesson.  There really isn't much to teach about operators, you use them as you need them.  And if you don't know if what you want exists, you just check the PHP documentation.

Check out PHP's documentation for explanations of all the operators:



Top Members

No top members yet.