Home >Backend Development >PHP Tutorial >Basic introduction to operators in php_PHP tutorial
The commonly used operators in PHP include arithmetic operators, assignment operators, comparison operators, logical operators, etc. Let me introduce the usage to my friends.
The division operator always returns a floating point number. The only exception is if both operands are integers (or integers converted from strings) and are exactly divisible, in which case it returns an integer.
The operands of the modulo operator will be converted to integers (except for the decimal part) before operation.
Note: The result of modulo $a % $b when $a is negative is also negative.
Example:
The code is as follows | Copy code | ||||
$a = 2863311530; $b = 256; $c = $a % $b; echo "$c n"; echo (2863311530 % 256)." n"; /* directly with no variables, just to be sure */ ?>
|
运算符 | 说明 | 例子 | 结果 |
---|---|---|---|
+ | Addition | x=2 x+2 |
4 |
- | Subtraction | x=2 5-x |
3 |
* | Multiplication | x=4 x*5 |
20 |
/ | Division | 15/5 5/2 |
3 2.5 |
% | Modulus (division remainder) | 5%2 10%8 10%2 |
1 2 0 |
++ | Increment | x=5 x++ |
x=6 |
-- | Decrement | x=5 x-- |
x=4 |
Assignment operator
The basic assignment operator is "=". At first you may think it is "equal to", but it is not. It actually means assigning the value of the expression on the right to the operand on the left.
The value of the assignment expression is the assigned value. That is, the value of "$a = 3" is 3. Here are some tips:
代码如下 | 复制代码 |
$a = ($b = 4) + 5; // $a 现在成了 9,而 $b 成了 4。 ?> |
The code is as follows | Copy code | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Note that the assignment operation copies the value of the original variable to the new variable (assignment by value), so changing one does not affect the other. This is also suitable for copying values such as large arrays in very dense loops. You can also use reference assignment, using the $var = &$othervar; syntax. Reference assignment means that both variables point to the same data, and there is no copy of any data. See the citation description for more information about citations. In PHP 5, objects are always assigned by reference unless explicitly using the new clone keyword
Comparison operators Comparison operators, as their name implies, allow comparison of two values. If you compare an integer and a string, the string is converted to an integer. If comparing two numeric strings, compare as integers. This rule also applies to switch statements.
Logical operators The reason why "AND" and "OR" have two different forms of operators is that the precedence of their operations is different (see operator precedence). Example #1 Logical operator example
$e = false || true; // $e is assigned the value (false || true), and the result is true $f = false or true; // $f is assigned false [Altair note: "=" has a higher priority than "or"] var_dump($e, $f);
|