2.5. Operators

PHP, like many other programming languages, provides a number of operators that allow you to manipulate data. These operators fall into several categories; this book walks you through taking advantage of the following operators:

  • Arithmetic Operators: These perform basic mathematical functions

  • Arithmetic Assignment Operators: These set expression values

  • Comparison Operators: These determine the similarity of two values

  • Error Control Operators: These special operators to suppress errors

  • Incrementing/Decrementing Operators: These increase or decrease a value

  • Logical Operators: These denote logical operations; examples include AND and OR

  • String Operators: These manipulate strings

2.5.1. Arithmetic Operators

The arithmetic operators in PHP function just like the ones you used in school.

The addition operator (+) returns the sum of two values:

echo 2 + 2; // Outputs 4

The subtraction operator (-) returns the difference between two values:

echo 4 − 2; // Outputs 2

The multiplication operator (*) returns the product of two values:

echo 4 * 2; // Outputs 8

The division operator (/) returns the quotient of two values:

echo 8 / 2; // Outputs 4

NOTE

The division operator (/) returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value is returned.[]

[] Quoted from the PHP Manual, "Arithmetic Operators," www.php.net/manual/en/language.operators.arithmetic.php

The modulus operator (%) returns the remainder of one value divided by another:

echo 7 % 2; // Outputs 1
echo 8 % 2; // Outputs 0

2.5.2. Arithmetic Assignment Operators

PHP provides several assignment operators that enable you to set the value of an operand to the value of an expression. You do this with an equals sign (=), but it's important to be aware that this sign does not mean "equals" as it is commonly understood; instead, this symbol means "gets set to." For example, consider this code snippet:

$a = 5,

Read aloud, the snippet actually says, "The value of $a gets set to five."

There are also a few combined operators that allow you to declare an expression and assign its value to an operand in one quick step. These operators combine an arithmetic operator with the assignment operator:

<?php

$foo = 2;

    $foo += 2; // New value is 4

    $foo -= 1; // New value is 3

    $foo *= 4; // New value is 12

    $foo /= 2; // New value is 6

    $foo %= 4; // New value is 2

?>

Note that PHP assigns by value. Thus, a variable assigned with a value copies the entire value into memory, rather than a reference to the original location of the value. In other words, assigning the value of a variable to the value of a second variable, and then changing the value of the second variable, does not affect the value of the initial variable:

<?php

    $foo = 2;
    $bar = $foo;

    echo $bar; // Output: 2

    $foo += 4; // New value is 6

    echo $bar; // Output: 2

?>

If you require the value of $foo to affect $bar after its declaration, or vice versa, then you need to assign by reference using an equals sign followed by an ampersand (=&). This is potentially useful for allowing a variable to be altered indirectly by a script. For instance, if you have an array that contains a person's basic information, you might assign the person's age by reference to account for a birthday.

You'll be using another output function that is extremely useful for debugging, called print_r(). This outputs a "human readable" display of the contents of variables. It is especially useful in debugging arrays:

<?php

    $person = array(
        'name' => 'Jason',
        'age' => 23
    );

$age =& $person['age'];

    // Output the array before doing anything
    print_r($person);

    // Birthday! Add a year!
    ++$age;

    // Output the array again to see the changes
    print_r($person);

?>

Running this script produces the following output:

Array
(
    [name] => Jason
    [age] => 23
)
Array
(
    [name] => Jason
    [age] => 24
)

2.5.3. Comparison Operators

You use comparison operators to determine the similarity between values. These are especially useful in control structures, which I'll cover in just a moment.

The available comparison operators allow you to determine whether the following conditions are present between two values:

  • (==): Values are equal

  • (===): Values are identical

  • (!= or <>): Values are not equal

  • (!==): Values are not identical

  • (<): Value 1 is less than value 2

  • (>): Value 1 is greater than value 2

  • (<=): Value 1 is less than or equal to value 2

  • (>=): Value 1 is greater than or equal to value 2

NOTE

Equal and identical are not the same thing. Identical matches both a variable's value and datatype, whereas equal matches only value. Boolean values are commonly checked with the identical comparison operator because FALSE==0 evaluates to TRUE, while FALSE===0 evaluates to FALSE. You'll use this technique several times throughout the book, so don't worry if it doesn't make perfect sense right now.

2.5.4. Error Control Operators

PHP offers one error control operator: the at symbol (@). This symbol temporarily sets the error reporting level of your script to 0; this prevents errors from displaying if they occur.

For example, trying to reference a nonexistent file with include_once (e.g., include_once 'fake_file';) would cause an error along these lines:

Warning: include_once(fake_file)
 [function.include-once]: failed to open stream: No such file or directory in
 /Applications/xampp/xamppfiles/htdocs/simple_blog/test.php on line 4

Warning: include_once() [function.include]: Failed opening 'fake_file' for
 inclusion (include_path='.:/Applications/xampp/xamppfiles/lib/php')
 in /Applications/xampp/xamppfiles/htdocs/simple_blog/test.php on line 4

That's a fairly verbose error, and you probably don't want our users to see something like that displayed on their screen. You can avoid this error by prepending the code with an at symbol:

<?php

    @include_once 'fake_file';

    echo 'Text to follow the include.';

?>

NOTE

Placing an operator sign before a variable is called prepending; this technique enables you to perform an operation on a variable before it is instantiated. Placing an operator after the variable is called postpending; this technique instantiates a variable first, and then performs an operation on it.

The file doesn't exist, and an error is generated, but the at symbol prevents the error from displaying and produces the following result:

Text to follow the include.

You should avoid using an error suppression operator whenever possible because it can adversely affect performance in your scripts. Alternative methods for catching errors exist, and I'll go into more details about those later on in the book.


2.5.5. Incrementing/Decrementing Operators

In some scripts, it becomes necessary to add or subtract one from a value quickly. PHP provides an easy way to do this with its incrementing and decrementing operators.

To add one to a value, add two plus signs (++) before or after the variable. To subtract one, add two minus signs (--)—remember that placing the (++) or (--) operators before a variable increments or decrements the variable before it is instantiated, while placing these operators after a variable increments or decrements the variable after it is instantiated. Adding signs in front of the variable is called prepending, which means the variable is incremented or decremented before it is instantiated:

<?php

    $foo = 5;
    ++$foo; // New value is 6
    $foo++; // New value is 7

    --$foo; // New value is 6
    $foo--; // New value is 5

    $bar = 4;

    // Echo a prepended value
    echo ++$bar; // Output is 5, new value is 5

    // Echo a postpended value
    echo $bar++; // Output is 5, new value is 6

?>

2.5.6. Logical Operators

It is difficult to cover the logical operators available in PHP without using control structures to illustrate how they work, so let's jump a little ahead and use the if statement to demonstrate how to use them.

Logical operators allow you to determine whether two conditions are true or not. This is very useful when using conditional statements to dictate what happens in a program. PHP's available operators include:

  • AND or &&: Returns true if both expressions are true

  • OR or ||: Returns true if at least one expression is true

  • XOR: Returns true if one expression is true, but not the other

  • !: Returns true if the expression is not true

You can place the following code in test.php for a practical demonstration of how these operators work:

<?php

    $foo = true;
    $bar = false;

    // Print the statement if $foo AND $bar are true
    if($foo && $bar) {
        echo 'Both $foo and $bar are true. <br />';
    }

    // Print the statement if $foo OR $bar is true
    if($foo || $bar) {
        echo 'At least one of the variables is true. <br />';
    }

    // Print the statement if $foo OR $bar is true, but not both
    if($foo xor $bar) {
        echo 'One variable is true, and one is false. <br />';
    }

    // Print the statement if $bar is NOT true
    if(!$bar) {
        echo '$bar is false. <br />';
    }

?>

Loading http://localhost/simple_blog/test.php should produce the following output:

At least one of the variables is true.
One variable is true, and one is false.
$bar is false.

Now, set $bar = true and reload. The output should now read:

Both $foo and $bar are true.
At least one of the variables is true.

NOTE

For an explanation of how the if statement works, see the section on Control Structures later in this chapter.

2.5.7. String Operators

There are two string operators available in PHP: the concatenation operator (.) and the concatenating assignment operator (.=). The concatenation operator combines two strings into one by joining the end of the string to the left of the operator to the beginning of the string on the right of the operator. The concatenating assignment operator adds a string to the end of an existing variable:

<?php

    $foo = "Hello";

    $bar = $foo . " world! <br />";

    echo $bar; // Output: Hello world!

    $bar .= " And again!";

    echo $bar; // Output: Hello world! And again!

?>

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

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