# PHP operators

2022-04-23 15:34:00

Arithmetic operator
Assignment operator
An operator
Comparison operator
Error control operators
The execution operator
Increasing （ reduce ） Operator
Logical operators
String operators
Array operators
Type operators
Operator priority

## Arithmetic operator

Common arithmetic operators include

-$a, Take the opposite$a + $b, Add ,a and a and b And$a - $b, Subtraction ,a and a and b Difference$a * $b, Multiplication ,a and a and b Product of$a / $b, division ,a and a and b The business of$a % $b, Remainder ,a Divide a Divide b The remainder of$a ** $b, chengfang ,a Of a Of b Power edit /home/project/arithmetic.php <?php$a = 9 / 3;
$b = 9 / 4;$c = -5 % 3;
$d = 5 % -3;$e = 2 ** -2;

echo <<<EOT 9 / 3 = $a 9 / 4 =$b -5 % 3 = $c 5 % -3 =$d 2 ** -2 = $e EOT;  perform php arithmetic.php It can be seen from the results • The division operator always returns a floating point number . Only in the following cases ： Both operands are integers （ Or an integer converted from a string ） And it can just divide , Then it returns an integer . • The operands of the remainder operator are converted to integers before operation （ Remove the decimal part ）. And the sign of the result and the divisor （ The sign ） identical . namely a %ab The result and$a The same symbol as .

## Assignment operator

The basic assignment operator is =, It 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 . in other words ,$a = 3 The value of is 3. So you can do some tricks ： <?php$a = ($b = 4) + 5; //$a  Now it's  9, and  $b a 4.  For arrays array, Assigning values to named keys is done with => Operator . This operator has the same priority as other assignment operators . <?php$a = ['a' => 1, 'b' => 3 * 4];


Outside the basic assignment operator , And for all binary arithmetic , Combination operator of array set and string operator , You can assign it a value to the result of such an expression , for example ：

<?php

$a = 3;$a += 5; // amount to  $a =$a + 5;
$b = "Hello ";$b .= "There!"; // amount to  $b =$b. "There" ;


Note that the assignment operation copies the value of the original variable into the new variable （ Pass value assignment ）, So changing one doesn't affect the other . This is also suitable for copying some values in a dense loop, such as a large array .

Reference assignment

PHP Support reference assignment , Reference assignment means that two variables point to the same data , Didn't copy anything .

edit /home/project/assign.php

<?php

$arr1 =$arr2 = [1,2,3];

foreach($arr1 as &$a) {

$a++; } foreach($arr2 as $a) {$a++;
}
print_r($arr1); print_r($arr2);


perform

php assign.php
As can be seen from the results , Reference assignment will change the original value , Value assignment will not .

## Comparison operator

Comparison operator , As their name implies , Allows two values to be compared .

• $a ==$b, If after type conversion a be equal to a be equal to b, return TRUE.
• $a ===$b, If a be equal to a be equal to b, And they're of the same type , return TRUE.
• $a !=$b, If after type conversion a It's not equal to a It's not equal to b, return TRUE.
• $a <>$b, Equate to !=
• $a !==$b, If a and a and b Different values or types , return TRUE.
• $a <$b , If a Strictly less than a Strictly less than b, return TRUE.
• $a >$b, If a Strictly greater than a Strictly greater than b, return TRUE.
• $a <=$b, If a Less than or equal to a Less than or equal to b, return TRUE.
• $a >=$b, If a Greater than or equal to a Greater than or equal to b, return TRUE.
If you compare a number to a string or a string that involves the contents of a number , The string will be converted to a numeric value and the comparison will be performed according to the numeric value . This rule also applies to switch sentence . When used === or !== When comparing, there is no type conversion , Because at this time, the type and value must be compared .

edit /home/project/compare.php

<?php

var_dump(null == "");
var_dump(null == false);
var_dump(true > false);
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("10" == "1e1");
var_dump(100 == "1e2");
var_dump([4,5] < [1,2,3]);
var_dump((object)"Test" > "Test");
var_dump((object)"Test" > [2,3]);

switch ("a") {

case 0:
echo "0";
break;
case "a":
echo "a";
break;
}


perform

php compare.php

It can be seen from the results

• null or String and string When comparing , take null Convert to “”, Compare numbers or words
• bool or null When compared with other types , Convert to bool,FALSE < TRUE
• string,resource or number When comparing with each other , Convert a string or resource to a number , Compare... By ordinary numbers
• array When comparing between , Arrays with fewer members are smaller
• object When compared with other types ,object Always bigger
• array When compared with other types ,array Always bigger , But smaller than the object
• switch When the first condition is satisfied , The following statements that meet the conditions will not be executed

## Increasing （ reduce ） Operator

Common incremental （ reduce ） Operator

• ++$a,a Add one to return a Add one to return a. • $a++, return a, And then a, And then a Add one to the value of .
• --$a,a Minus one returns a Minus one returns a. • $a--, return a, And then a, And then a Value of minus one .
Increasing （ reduce ） Operator on Boolean and NULL Impact of type
<?php

$a = null;$b = true;

var_dump(++$a, --$a, ++$b, --$b);


Results output

int(1)
int(0)
bool(true)
bool(true)


Boolean values are not affected ,NULL Increment to 1, Decrement to 0

edit /home/project/xcre.php

<?php

$a = 0;$i = 'W';
while($a < 6) { echo "$a : ".++$i . PHP_EOL;$a++;
}


perform

php xcre.php

From the results, we can see

When dealing with the arithmetic operation of character variables ,PHP Followed Perl The habit of , Instead of C Of . for example

$a = 'Z'; // Perl in$a++;// Will put  $a become 'AA' //C in$a++;// Will put  $a become '['（'Z' Of ASCII The value is 90,'[' Of ASCII The value is 91）  Note that character variables can only be incremented , Not decreasing , And only pure letters are supported （a-z and A-Z）. Increasing （ reduce ） Other character variables are not valid , The original string has not changed . ## Logical operators Common logical operators •$a and $b, Logic and , If a and a and b All for TRUE •$a && $b, Logic and , If a and a and b All for TRUE, among && Priority over and •$a or $b, Logic or , If a or a or b Any for TRUE •$a || $b, Logic or , If a or a or b Any for TRUE,|| Priority over or •$a xor $b, Logical XOR , If a or a or b Any for TRUE, But not at the same time , Then return to TRUE • !$a, Logic is not , If $a Not for TRUE edit /home/project/logical.php <?php$a = (false && foo());
$b = (true || foo());$c = (false and foo());
$d = (true or foo()); var_dump($a, $b,$c, $d);$e = false || true;
$f = false or true;$g = true && false;
$h = true and false; var_dump($e, $f,$g, $h);  perform php logical.php From the results, we can see foo() Although there is no definition , But there is no chance to implement , Because the previous expression has determined the result ,foo() Short circuited . &&,|| Has a higher priority than =,= Has a higher priority than and,or. ## String operators There are two string operators . • The first is the join operator ., It returns the string connected by its left and right parameters • The second is the join assignment operator .=, It appends the right parameter to the left parameter . <?php$a = "Hello ";
$b =$a . "World!"; // now $b contains "Hello World!"$a = "Hello ";
$a .= "World!"; // now$a contains "Hello World!"


Click the environment window below , Start actual combat

## Array operators

Common array operators

• $a +$b,a and a and b Union
• $a ==$b,a and a and b If the key and value are the same, it is TRUE
• $a ===$b,a and a and b Keys and values in the same order and type return TRUE
• $a !=$b,a and a and b If the middle key or value is different, return TRUE
• $a <>$b, Equate to !=
• $a !==$b,a and a and b In the key , value , Order or type , If one of them is different, it returns TRUE
edit /home/project/array.php
<?php

$a = ["a" => "apple", "b" => "banana"];$b = ["a" => "pear", "b" => "strawberry", "c" => "cherry"];
echo "<pre>$output</pre>";  Be careful , The backquote operator activates safe mode or turns off shell_exec() Time is invalid . ## Error control operators PHP Supports an error control operator ：@. When placing it in a PHP Before expression , Any error messages that this expression may generate are ignored . <?php$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");$value = @$cache[$key];


Error control operators are only valid for expressions . A simple rule for beginners is ：

• If you can get value from somewhere , You can put... In front of it @ Operator . for example , You can put it in variables , Functions and include call , Constant , Wait, before .
• It cannot be placed before the definition of a function or class , Nor can it be used for conditional structures such as if and foreach etc. .

Be careful ： current @ The error control operator prefix invalidates even error reports of serious errors that cause the script to terminate .

This means that if you use... Before a function call that does not exist or has the wrong letter @ To suppress error messages , The script will show no sign of the cause of death there .

## An operator

Bit operators allow evaluation and manipulation of the bits specified in an integer number .

$a &$b,And（ Bitwise AND ）, Will put a and a and b All of them are for 1 The bit of is set to 1.
$a |$b,Or（ Press bit or ）, Will put a and a and b Any one of them is 1 The bit of is set to 1.
$a ^ b , X o r （ Press position different or ） , take hold a and a and b in One individual by 1 another One individual by 0 Of position set up by 1 . b,Xor（ Bitwise XOR ）, Will put a and a and b One of them is 1 For another 0 The bit of is set to 1. ~ a,Not（ According to the not ）, take$a In Chinese, it means 0 The bit of is set to 1, vice versa .
$a <<$b,Shift left（ Move left ）, take a The position in is shifted to the left a The position in is shifted to the left b Time （ Every move means multiplying by 2）.
$a >>$b,Shift right（ Move right ）, take a The position in moves to the right a The position in moves to the right b Time （ Every move is divided by 2）.
Example 1 The integer AND,OR and XOR An operator .

<?php
/* * Ignore the top section, * it is just formatting to make output clearer. */

$format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)' . ' %3$s (%4$2d = %4$04b)' . "\n";

echo <<<EOH --------- --------- -- --------- result value op test --------- --------- -- --------- EOH;

/* * Here are the examples. */

$values = array(0, 1, 2, 4, 8);$test = 1 + 4;

echo "\n Bitwise AND \n";
foreach ($values as$value) {

$result =$value & $test; printf($format, $result,$value, '&', $test); } echo "\n Bitwise Inclusive OR \n"; foreach ($values as $value) {$result = $value |$test;
printf($format,$result, $value, '|',$test);
}

echo "\n Bitwise Exclusive OR (XOR) \n";
foreach ($values as$value) {

$result =$value ^ $test; printf($format, $result,$value, '^', $test); } ?>  The above routine will output ： --------- --------- -- --------- result value op test --------- --------- -- --------- Bitwise AND ( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101) ( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101) ( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101) ( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101) ( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101) Bitwise Inclusive OR ( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101) ( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101) ( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101) ( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101) (13 = 1101) = ( 8 = 1000) | ( 5 = 0101) Bitwise Exclusive OR (XOR) ( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101) ( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101) ( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101) ( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101) (13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)  ## PHP7 New operator Combination comparator The spacecraft operator uses <=> Express , Used to compare two expressions . When a Less than 、 Equal to or greater than a Less than 、 Equal to or greater than b When it returns to -1、0 or 1. The principle of comparison is to use PHP The regular comparison rules of . <?php // Integers echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floating point numbers echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // character string echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 ?>  NULL coalescing operator NULL The merge operator uses ?? Express , It means if ?? The previous variable exists and the value is not NULL, It will return its own value , Otherwise return to ?? Operand after . < ?php$username = $_GET['user'] ?? 'nobody';$username = isset($_GET['user']) ?$_GET['user'] : 'nobody';

$username =$_GET['user'] ?? \$_POST['user'] ?? 'nobody';


Merge operators can usually be replaced by ternary operators , Multiple merge operators are executed at one time from left to right .

https://yzsam.com/2022/04/202204231526352610.html