Главная » Мастерская » Статьи » Документация по PHP

Операторы

Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.

The following table lists the precedence of operators with the lowest-precedence operators listed first.
Таблица 1. Operator Precedence
AssociativityOperators
left,
leftor
leftxor
leftand
rightprint
left= += -= *= /= .= %= &= |= ^= ~= <<= >>=
left? :
left||
left&&
left|
left^
left&
non-associative== != === !==
non-associative< <= > >=
left<< >>
left+ - .
left* / %
right! ~ ++ -- (int) (float) (string) (array) (object) @
right[
non-associativenew

Arithmetic Operators

Remember basic arithmetic from school? These work just like those.
Таблица 2. Arithmetic Operators
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.

The division operator ("/") returns a float value anytime, even if the two operands are integers (or strings that get converted to integers).

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the the left operand gets set to the value of the expression on the rights (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. PHP 4 supports assignment by reference, using the $var = &$othervar; syntax, but this is not possible in PHP 3. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained.

Bitwise Operators

Bitwise operators allow you to turn specific bits within an integer on or off. If both the left- and right- hand parameters are strings, the bitwise operator will operate on the characters in this string.

<?php
    echo 12 ^ 9; // Outputs '5'

    echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                     // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

    echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                            // 'a' ^ 'e' = #4
?>
Таблица 3. Bitwise Operators
ExampleNameResult
$a & $bAndBits that are set in both $a and $b are set.
$a | $bOrBits that are set in either $a or $b are set.
$a ^ $bXorBits that are set in $a or $b but not both are set.
~ $aNotBits that are set in $a are not set, and vice versa.
$a << $bShift leftShift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $bShift rightShift the bits of $a $b steps to the right (each step means "divide by two")

Comparison Operators

Comparison operators, as their name implies, allow you to compare two values.
Таблица 4. Comparison Operators
ExampleNameResult
$a == $bEqualTRUE if $a is equal to $b.
$a === $bIdenticalTRUE if $a is equal to $b, and they are of the same type. (PHP 4 only)
$a != $bNot equalTRUE if $a is not equal to $b.
$a <> $bNot equalTRUE if $a is not equal to $b.
$a !== $bNot identicalTRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only)
$a < $bLess thanTRUE if $a is strictly less than $b.
$a > $bGreater thanTRUE if $a is strictly greater than $b.
$a <= $bLess than or equal toTRUE if $a is less than or equal to $b.
$a >= $bGreater than or equal toTRUE if $a is greater than or equal to $b.

Another conditional operator is the "?:" (or ternary) operator, which operates as in C and many other languages.

(expr1) ? (expr2) : (expr3);

This expression evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. $a == $b$a === $b$a != $b$a <> $b$a !== $b$a < $b$a > $b$a <= $b$a >= $b

Another conditional operator is the "?:" (or ternary) operator, which operates as in C and many other languages.

(expr1) ? (expr2) : (expr3);

This expression evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the global variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Замечание: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting().

Внимание

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable).

$output = `ls -al`;
echo "<pre>$output</pre>";

Замечание: The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

See also escapeshellcmd(), exec(), passthru(), popen(), shell_exec(), and system().

Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Таблица 4. Comparison Operators
ExampleNameResult
EqualTRUE if $a is equal to $b.
IdenticalTRUE if $a is equal to $b, and they are of the same type. (PHP 4 only)
Not equalTRUE if $a is not equal to $b.
Not equalTRUE if $a is not equal to $b.
Not identicalTRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only)
Less thanTRUE if $a is strictly less than $b.
Greater thanTRUE if $a is strictly greater than $b.
Less than or equal toTRUE if $a is less than or equal to $b.
Greater than or equal toTRUE if $a is greater than or equal to $b.
Таблица 5. Increment/decrement Operators
ExampleNameEffect
++$aPre-incrementIncrements $a by one, then returns $a.
$a++Post-incrementReturns $a, then increments $a by one.
--$aPre-decrementDecrements $a by one, then returns $a.
$a--Post-decrementReturns $a, then decrements $a by one.

Here's a simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

Logical Operators

Таблица 6. Logical Operators
ExampleNameResult
$a and $bAndTRUE if both $a and $b are TRUE.
$a or $bOrTRUE if either $a or $b is TRUE.
$a xor $bXorTRUE if either $a or $b is TRUE, but not both.
! $aNotTRUE if $a is not TRUE.
$a && $bAndTRUE if both $a and $b are TRUE.
$a || $bOrTRUE if either $a or $b is TRUE.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"

Array Operators

The only array operator in PHP is the + operator. It appends the right handed array to the left handed, whereas duplicated keys are NOT overwritten.

$a = array("a" => "apple", "b" => "banana");
$b = array("a" =>"pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b;

var_dump($c);

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

Copyright ByWeb©
Hosted by uCoz