Operators

An operator is a helper in PHP that deals with one or more values and returns a different value. This may seem very vague, but operators are everywhere. Think about a math class. When you do basic addition, what are you doing? You are taking in two values (7 and 5, for example), adding them together (7 + 5), and receiving a different value (12). In this case, the plus sign is the operator causing the change.

Think about the gettype() function that we went over in Chapter 4. This function takes in a variable name and returns its type. This function is an operator because it takes in a value (the variable) and results in something different (a type). Sure, these two pieces of data may be different, but the function still acts upon it!

There are three classes of operators.

Note

Even though functions do act upon data, we generally don’t think of functions as operators. We consider functions to be their own type of construction, and just deal with PHP default operators as operators.


Unary

A unary operator acts only upon one input. For example, the ++ operator increments a variable by 1. For example, assume you type the following:

$x = 10
$x++;
$echo $x;

You get the result 11.

Binary

Binary operators act upon two pieces of data. Think about the addition problem I just mentioned. There were two pieces of data: 5 and 7. Both of these, along with the operator ±, achieve a new result. Binary operators include arithmetic operators such as multiplication and division, as well as testing operators such as greater than or less than.

Ternary

There is only one ternary operator. This one is a little weird if you have never seen it before, and it is used a lot less than the binary operators, but it can be powerful when used correctly. The operator is called the ?: operator because it works with three sets of data. The first set comes before the question mark, and it is a test; for example, $x>$y determines whether $x is greater than $y.

  • If the test is true, then the result is after the question mark (but before the colon).

  • If the test is false, then the result is after the colon.

Before going into the rest of the operators, look at an example using the ternary operator. If you want to do the same test to check if $x is larger than $y, you might want to echo out the results. Take a look at the following PHP document, then check out Figure 5.3 to see the result:

Figure 5.3. The phpft05-03.php ternary operator file.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Using the ternary operator</title>
</head>
<body>
<?php

$x = 7;
$y = 10;

//If x is greater than y, $ans = "greater", otherwise it equals "less"
$ans = ($x > $y) ? "greater" : "less";

//Print out the result
echo "<p>After the test, we have determined that $x is $ans than $y</p>";

?>
</body>

</html>

In this case, we gave variable values to $x and $y. We then used the ternary operator to give a value to the variable $ans, which could have the result of greater or less, depending on whether $x is greater than or less than $y. Let’s take an in-depth look.

$ans = ($x > $y) ? "greater" : "less";

First, $ans is created and is left to the side to be assigned to the operation results. Next, the operator tests the expression ($x > $y). If this is true, then the first result is returned: greater. If the test is false, then the second result is returned: less. Because $ans is assigned to the result, it can only be either greater or less. In this example, $x was not greater than $y, so the result was false and $ans was less. We then plugged this value into an echo statement:

echo "After the test, we have determined that $x is $ans than $y";

This statement echoes the results. First, it writes out "After the test, we have determined that .". Then it writes out the value of $x, followed by is, displays the $ans value, and shows than $y". Because $ans can only be greater or less, it will make a valid sentence. By the way, if $x and $y are both equal to the same number, the program is blank. In a real program, you need to handle that event.

You might have noticed that I used a different scheme to write out the echo statement. Earlier, we used single quotes to echo out text; here I used double quotes. Check out the sidebar to find out why.

Why can I echo with double quotes or single quotes?

When using an echo command (or any command that requires quotation marks), consider whether you want to use single or double quotes. When writing out basic text, there is no difference. For example, echo 'Hello, World!' is identical to echo "Hello, World!". However, when you use variables or constants within an echo statement, double quotes and single quotes are very different. Double quotes allow you to place a variable directly into the string, referenced by a $ symbol; PHP substitutes the variable’s value. However, with single quotes, the value is not substituted; instead, the page displays the quote’s name. To use variables within single-quoted statements, you need to use the dot operator (.), ending the string with a single quote and using the dot operator to join a variable and the string.


Arithmetic Operators

Arithmetic operators are the most common. Most are basically the same ones you have known your entire life: addition, subtraction, multiplication, and division. Arithmetic operators act just like you would expect them to when you do something like what you see in Table 5.1.

Table 5.1. Arithmetic Operators
TaskSymbolExample
Add two numbersAddition (+)$sum = $a + $b
Subtract two numbersSubtraction ()$different = $a – $b
Multiply two numbersAsterisk (*)$product = $a * $b
Divide two numbersForward slash (/)$quotient = $a / $b
Retrieve a negative numberSubtraction ()$negative = − $a
Retrieve a division remainderPercentage (%)$remainder = $a % $b?

The last two might be new to you. The negative operator returns the number’s negative value. For example, using the negative operator on 7 would return -7. This operator is a unary operator, meaning it only works on one input. The last arithmetic operator is called the modulus operator. It works in the same way as any of the binary operators. For instance, 7%7 would return 0 because there is no remainder in a 7/7 division problem. In 9%7, the answer is 2, because there is a remainder. Modulus is awesome for checking some specific things, such as if a number is even or odd. 6%2 is 0, meaning the number (6) is even, and 5%2 is odd (and it is equal to 1), meaning that 5 is odd. If you are checking remainders, modulus is excellent for that purpose.

Let’s put all these arithmetic operators into a program. We will use a basic calculator form. Here is the form that we created to do this job. You can find it on the CD as phpft05-04.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>
<title>A Basic Arithmetic Calculator</title>
</head>

<body>
<form name="calculator" method="get" action="phpft05-04.php">
<p>
Enter your first value:
<input type="text" name="first" />
<p>Choose an operation:
<select name="operation">
<option value="+">+
<option value="−">−
<option value="*">*
<option value="/">/
<option value="%">%

</select>

<p>
Enter your second value:
<input type="text" name="second" />
<p>
<input type="submit" >
</form>

</body>

</html>

This looks like Figure 5.4, where I substituted some sample values.

Figure 5.4. The phpft05-03.htmlcalculator form file.


As you can see, this creates a sample form which sends its data through the GET method to a PHP file. The form code also creates a cool drop-down box, pictured in Figure 5.5.

Figure 5.5. A drop-down box.


The following <select> HTML element makes the drop-down box show up:

<select name="operation">

<option value="+">+
<option value="−">−
<option value="*">*
<option value="/">/
<option value="%">%

</select>

Each option has a value, which you set. When using PHP, the selected option is passed into the $_GET[] or $_POST[] variable, just as if the user had entered the value in a textbox. Therefore, if the user selects /, the $_GET['operation'] variable will be equal to /.

Now, the PHP document is a little more complex than anything we have seen so far. Check out the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>PHP Calculator</title>
</head>

<body>
<?php
//put form variables in standard variables
$a = $_GET['first'];
$b = $_GET['second'];
$op = $_GET['operation'];

echo "The result of your expression, $a $op $b is ";

//Check the operation and deal with the result correctly
if($op=='+')
{
  echo $a + $b;
}

if($op=='-')
{
  echo $a - $b;
}

if($op=='*')
{
  echo $a * $b;
}

if($op=='/')
{
  echo $a/$b;
}

if($op=='%')
{
  echo $a%$b;
}

?>
</body>

</html>

That’s pretty crazy, huh? Check out the results in Figure 5.6.

Figure 5.6. The phpft05-04.php file.


This page introduces you to something new: conditional statements. For this page, you have to do something different depending on what operator the user chooses. Because of this, we use the if statements you see in the preceding code. Basically, the statement tests whether something is true. This test is within the parentheses after the word if. If the test is true, then whatever is in the curly braces ('{' '}') occurs. If not, then the statement doesn’t occur. (I go over this in depth in the next part, when I talk about conditional statements. I wanted to introduce this here because if statements are everywhere and it helps to understand what they do, even if you can’t write them yourself yet.)

One other thing to notice in this page: This is the first time we used the GET method rather than POST. Take a look at the address bar after filling out the form and pressing submit. Figure 5.7 shows you what mine says.

Figure 5.7. The address bar using the GET method.


You see the tricky part? It actually encodes the variables within the address bar. This means that you can see the variables you passed along with the form just by looking at the URL. This also means that you can bookmark the results, and they will continue to show the correct results. With the POST method, you lose the form results each time. Also, Figure 5.8 shows what happens when I change the address bar to pass / rather than * for the operator. You can see here that it actually changes the page results.

Figure 5.8. Changing the variables in a GET form.


Using GET is great for pages where you want a visitor to be able to return. Since the data is stored in the URL, the user can easily bookmark the page with the correctly inputted information and access the interpreted data without submitting the form each time. However, GET has some drawbacks:

  • There is a URL-length limit that prevents you from having unlimited variables in the page.

  • Information is not secure. When passing secure information, such as a password, it is much better to use POST so that the sensitive data is not shown in the address bar.

Comparison Operators

Take a look at the PHP document. See how the if statements test for equality using the == operator? That’s a comparison operator. Comparison operators allow you to test two values against each other, and if they relate correctly, the test returns true. If the relationship specified by the test is incorrect, the return value is false. All comparison operators are binary, meaning they take two values in for input. Take a look at Table 5.2 for all of them.

Table 5.2. Comparison Operators
TaskSymbolExample
Return true if values are equal.Equal (=)$a == $b
Return true if values are equal and the same type.Identical (===)$a === $b
Return true if the values are not equal.Not equal (<>)$a != $b or $a <> $b
Return true if the values are unequal or are different types.Not identical (!==)$a !== $b
Return true if the first value is less than the second.Less than (<)$a < $b
Return true if the first value is larger than the second.Greater than (>)$a > $b
Return true if the first value is less than or equal to the second.Less than or equal to (<=)$a <= $b
Return true if the first value is greater than or equal to the second.Greater than or equal to (>=)$a >= $b

These operators can be used within any type of flow-control system, such as if tests or, as you learn later, switch tests. They are great tools for checking values.

Note

Keep in mind that the equality operator (==) is different than the assignment operator (=). The assignment operator changes the variable on the left to have a new value, while the equality variable tests for equality and returns a 1 if true.


Logical Operators

Logical operators are used when two or more comparisons are needed for a test. For example, you would use a logical operator if you needed to determine that $number is greater than 7 and also less than 10. With logical operators, you can do this and execute a statement only if $number is equal to 8 or 9. Table 5.3 lists the logical operators. For this table, $a and $b are comparisons, so in the preceding example, $a would be $number > 7 and $b would be $number < 10.

Table 5.3. Logical Operators
TaskSymbolExample
Return true if both comparisons are true.and$a and $b
Return true if either comparison is true or both comparisons are true.or$a or $b
Return true if either comparison is true, but not both.xor$a xor $b
Return true is the comparison is not true.!!$a
Return true if both comparisons are true.&&$a && $b
Return true if either comparison is true or both comparisons are true.||$a || $b

Precedence can be an issue with logical operators. Be careful to always use parentheses. Here’s an example: Pretend that you have three different statements—A, B, and C. Here are two different tests:

  • (A and B) or C

  • A and (B or C)

The test in the parentheses is always executed first.

Other Operators

A few more operators don’t really fit into the other categories, but you should know them because they are useful.

Assignment

You know this one already, because you used it to create a variable. This operator uses the = symbol, and it assigns a value to a variable. For example, the following is an assignment operation:

$x = 13;

The variable $x has the value 13. This assignment operation returns the value of the assignment, so if you set a new variable equal to the result of this operation, it is also equal to 13.

Incrementing and Decrementing

The operators add 1 to the value of an integer, meaning they are all unary. Look at the following samples of incrementing (the first two) and decrementing operators (the last two):

$a++
$++a
$a--
$--a

The value of each number increases by 1 when using the ++ operator and decreases by 1 when using the -- operator. For example, look at the following:

$a = 10;
$a++;
echo $a;
$a--;
echo $a

The variable $a is given a starting value of 10. It is then incremented, and the first echo statement shows the variable as having a value of 11. The second echo statement shows $a as having the value of 10, because the -- operation decrements it.

Note

You might be wondering why both operators can be attached to either the beginning or the end of the variable name. Attaching it to the front versus the back has similar results, but there is one important difference: When attaching the operator to the front, the variable is incremented by 1, and then the new value is returned. When the operator is attached to the back, the old value of the operator is returned, and then the variable is incremented by 1. For example, look at the following code:

$a=10;
$a++;
10;
++$a

The first echo statement will show the variable as being equal to 10, but immediately after the echo, the variable becomes 11. On the second echo statement, the variable becomes 11 and then the variable is echoed.


String Dot Operator and Dot Assignment

The string dot operator attaches different parts of strings together to form one big string. Take a look at the following code:

$firstpart = "Welcome to ";
$secondpart= "my web site. ";
$fullstring = $firstpart . $secondpart;

$fullstring now contains the value "Welcome to my web site." The dot operator joins the two parts of the string.

The dot assignment operator (.=) appends a new string to the end of the first string. For example, the following code puts in "Welcome to my web site.":

$text = "Welcome to ";
$text .= "my web site."

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.56.114