[PHP series tutorial] (7) Operators in PHP

Source: Internet
Author: User
1. The priority operator priority specifies how closely two expressions are bound. For example, the result of expression 1 + 5*3 is 16 instead of 18 because the priority of the multiplication sign (*) is higher than that of the plus sign (+. If necessary, use parentheses to forcibly change the priority. Example: (1 + 5) The value of * 3 is 18. The following table lists the operators from low to high.

1. The priority operator priority specifies how closely two expressions are bound. For example, the result of expression 1 + 5*3 is 16 instead of 18 because the priority of the multiplication sign (*) is higher than that of the plus sign (+. If necessary, use parentheses to forcibly change the priority. Example: (1 + 5) The value of * 3 is 18. The following table lists the operators from low to high.

I. Operator priority

The operator priority specifies how closely two expressions are bound ". For example, the result of expression 1 + 5*3 is 16 instead of 18 because the priority of the multiplication sign ("*") is higher than that of the plus sign ("+. If necessary, use parentheses to forcibly change the priority. Example: (1 + 5) The value of * 3 is 18.

The following table lists the operator priorities from low to high.

Integration direction Operator
Left ,
Left Or
Left Xor
Left And
Right Print
Right = + =-= * =/=. = % = & = | = ^ = ~ = <=> =
Left ? :
Left |
Left &&
Left |
Left ^
Left &
None =! ===! =
None <=> =
Left <>
Left + -.
Left */%
Right ! ~ ++ -- (Int) (float) (string) (array) (object )@
Right [
None New

Note: though! Higher than =, PHP still allows expressions similar to the following

Ii. Arithmetic Operators

Example Name Result
$ A + $ B Addition Sum of $ a and $ B.
$ A-$ B Subtraction The difference between $ a and $ B.
$ A * $ B Multiplication The product of $ a and $ B.
$ A/$ B Division $ A divided by $ B.
$ A % $ B Modulo Divide $ a by the remainder of $ B.

The division sign ("/") always returns a floating point number, even if the two operations are integers (or integers converted from strings.

Iii. assignment operators

The basic assignment operator is "= ". At first, you may think it is "equal", but it is not. It actually means assigning the value of the right expression to the number of left operations.

The value of the value assignment expression is the value assigned. That is to say, the value of "$ a = 3" is 3. In this way, you can do some tips:

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

In addition to basic value assignment operators, there are also "groups and operators" suitable for all binary and string operators ", this allows you to use its value in an expression and assign the result of the expression to it. 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: The value assignment operation copies the value of the original variable to the new variable (passing the value assignment), so changing one does not affect the other. This is also suitable for copying values such as large values in a tight loop. PHP 4 supports Reference Assignment and uses the $ var = & $ othervar; Syntax, but this is not possible in PHP 3. "Reference Value assignment" means that both variables point to the same data without any data copy.

Iv. bitwise operators

This operator allows you to set the specified bit in an integer. If both the left and right parameters are strings, bitwise operators operate on the characters in the 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?>

The bitwise operation table is as follows:

Example Name Result
$ A & $ B And (bitwise And) Set the bitwise of 1 in both $ a and $ B to 1.
$ A | $ B Or (by bit Or) Set the value of 1 in $ a or $ B to 1.
$ A ^ $ B Xor (by bit or) Set the bits in $ a and $ B to 1.
~ $ Not (non-by-bit) Set the bits 0 in $ a to 1, and vice versa.
$ A <$ B Shift left (left Shift) Move the bits in $ a to the left for $ B (each movement represents "multiplied by 2 ").
$ A> $ B Shift right (right Shift) Move the bits in $ a to the right $ B (each movement indicates "divided by 2 ").

5. Comparison Operators

Comparison operators, as their names imply, allow you to compare two values.

Example Name Result
$ A = $ B Equal TRUEIf $ a is equal to $ B.
$ A ===$ B Full TRUEIf $ a is equal to $ B, and their types are the same. (PHP 4 only)
$! = $ B Not Supported TRUEIf $ a is not equal to $ B.
$ A <> $ B Not Supported TRUEIf $ a is not equal to $ B.
$! ==$ B Incomplete TRUEIf $ a is not equal to $ B, or they are of different types. (PHP 4 only)
$ A <$ B Xiaohe TRUEIf $ a is strictly less than $ B.
$ A> $ B Greater TRUEIf $ a is strict with $ B.
$ A <= $ B Less than or equal TRUEIf $ a is less than or equal to $ B.
$ A> = $ B Greater than or equal TRUEIf $ a is greater than or equal to $ B.

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

<? Php // Example usage for: Ternary Operator $ action = (empty ($ _ POST ['action'])? 'Default': $ _ POST ['action']; // The above is identical to this if/else statementif (empty ($ _ POST ['action']) {$ action = 'default';} else {$ action = $ _ POST ['action'];}?>

For expressions (expr1 )? (Expr2): (expr3). If the value of expr1 is TRUE, the value of this expression is expr2. If the value of expr1 is FALSE, the value of this expression is expr3.

6. Error Control Operators

PHP supports an error control operator :@. Before placing the expression in a PHP expression, any error information that may be generated by the expression is ignored.

If the track_errors feature is activated, any error messages generated by the expression are stored in the variable $ php_errormsg. This variable will be overwritten every time an error occurs, so if you want to use it, you should check it as soon as possible.
<? 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.?>

Note: The @ operator is only valid for expressions. A simple rule for beginners is: if you can get a value from somewhere, you can add the @ operator before it. For example, you can place it before variables, functions, include () calls, constants, and so on. It cannot be placed before the definition of a function or class, nor can it be used for condition structures such as if and foreach.

Warning the current "@" error control operator prefix even invalidates the error reports that cause serious errors caused by script termination. This means that if you use "@" to suppress the error message before calling a function that does not exist or has a type error, the script will not show any evidence of the cause and die there.

VII. Execution Operators

PHP supports an execution OPERATOR: backquotes (''). Note that this is not a single quotation mark! PHP will try to execute the content in the back quotes as a shell command and return its output information (for example, it can be assigned to a variable rather than simply discarded to the standard output ). The effect of using the unquoted operator "'" is the same as that of the shell_exec () function.

<? Php $ output = 'LS-al'; echo "<pre> $ output </pre>";?>

Note: The Ampersand operator is invalid when safe mode is activated or shell_exec () is disabled.

8. plus and minus Operators

PHP supports the C-style prefix/suffix plus and minus operators.

Example Name Effect
++ $ Add Add one to the value of $ a, and then return $.
$ A ++ Houjia Returns $ a and adds the value of $ a to one.
-- $ Minus The value of $ a is reduced by one, and $ a is returned.
$ -- Subtraction $ A is returned, and then the value of $ a is reduced by one.

A simple example script:

<? Phpecho "Postincrement"; $ a = 5; echo "shocould be 5 :". $ a ++. "<br/>/n"; echo "shocould be 6 :". $. "<br/>/n"; echo "Preincrement"; $ a = 5; echo "shocould be 6 :". ++ $. "<br/>/n"; echo "shocould be 6 :". $. "<br/>/n"; echo "Postdecrement"; $ a = 5; echo "shocould be 5 :". $ --. "<br/>/n"; echo "shocould be 4 :". $. "<br/>/n"; echo "Predecrement"; $ a = 5; echo "shocould be 4 :". -- $. "<br/>/n"; echo "S Hocould be 4: ". $ a." <br/>/n ";?>

When processing the arithmetic operation of character variables, PHP follows the Perl habit, not C. For example, in Perl, 'z' + 1 will get 'A', and in C, 'z' + 1 will get '[' {ord ('Z ') = 90, ord ('[') = 91 ).

Code 1: arithmetic operation involving character Variables
<? Php $ I = 'W'; for ($ n = 0; $ n <6; $ n ++) echo ++ $ I. "/n";/* Produces the output similar to the following: XYZAAABAC */?>

9. logical operators

"And" and "or" have two different operators because they have different operation priorities.

Example Name Result
$ A and $ B And (logical And) TRUEIf both $ a and $ B areTRUE.
$ A or $ B Or (logical Or) TRUEIf either $ a or $ B isTRUE.
$ A xor $ B Xor (logical exclusive or) TRUEIf either $ a or $ B isTRUEBut not at the same time.
! $ Not (logical non) TRUEIf $ a is notTRUE.
$ A & $ B And (logical And) TRUEIf both $ a and $ B areTRUE.
$ A | $ B Or (logical Or) TRUEIf either $ a or $ B isTRUE.

9. String Operators

There are two string operators. The first is the concatenation operator ("."), which returns the string after the left and right parameters are connected. The second is the concatenation of the value assignment operator (". ="), which attaches the parameter on the right to the parameter on the left.

$ A = "Hello"; $ B = $ a. "World! "; // Now $ B contains" Hello World! "$ A =" Hello "; $ a. =" World! "; // Now $ a contains" Hello World! "

9. array Operators

The only array operator in PHP is the + operator. It attaches the array on the right to the array on the left, but duplicate key values are not overwritten.

$ A = array ("a" => "apple", "B" => "banana"); $ B = array ("a" => "pear ", "B" => "strawberry", "c" => "cherry"); $ c = $ a + $ B; var_dump ($ c );

After the script is executed, the script displays:

Array (3 ){
["A"] =>
String (5) "apple"
["B"] =>
String (6) "banana"
["C"] =>
String (6) "cherry"
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.