当前位置:网站首页>PHP operators
PHP operators
2022-04-23 15:34:00 【Jimeng network worry free】
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"];
$c = ["b" => "banana", "a" => "apple"];
var_dump($a + $b, $b + $a);
var_dump($a == $c, $a === $c);
perform
php array.php
It can be seen from the results
- Operator takes the array element on the right ( Remove those elements with the same key value as the array element on the left ) Append to the array on the left , However, duplicate key values will not be overwritten .
===, Array keys are required , value , The type and order are the same , To return to TRUE.
The execution operator
PHP Support an execution operator : The quotation marks (``). Note that this is not a single quotation mark !PHP Will try to execute the contents of the backquote as a shell command , And return its output information to ( for example , You can assign a variable instead of simply discarding it to standard output ).
<?php
$output = `ls -al`;
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. ~ b,Xor( 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. 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 .
版权声明
本文为[Jimeng network worry free]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231526352610.html
边栏推荐
- Differential privacy (background)
- 基础贪心总结
- Node. JS ODBC connection PostgreSQL
- regular expression
- Special analysis of China's digital technology in 2022
- Machine learning - logistic regression
- Openstack theoretical knowledge
- Multitimer V2 reconstruction version | an infinitely scalable software timer
- Llvm - generate for loop
- 移动金融(自用)
猜你喜欢
TLS / SSL protocol details (28) differences between TLS 1.0, TLS 1.1 and TLS 1.2
regular expression
Multitimer V2 reconstruction version | an infinitely scalable software timer
Kubernetes详解(九)——资源配置清单创建Pod实战
Kubernetes详解(十一)——标签与标签选择器
Mysql database explanation (IX)
重定向和请求转发详解
Tun model of flannel principle
Byte interview programming question: the minimum number of K
Squid agent
随机推荐
C语言超全学习路线(收藏让你少走弯路)
码住收藏▏软件测试报告模板范文来了
[backtrader source code analysis 18] Yahoo Py code comments and analysis (boring, interested in the code, you can refer to)
调度系统使用注意事项
KNN, kmeans and GMM
API gateway / API gateway (II) - use of Kong - load balancing
PSYNC synchronization of redis source code analysis
Demonstration meeting on startup and implementation scheme of swarm intelligence autonomous operation smart farm project
[leetcode daily question] install fence
深度学习调参的技巧
通过 PDO ODBC 将 PHP 连接到 MSSQL
MySQL installation process (steps for successful installation)
Three uses of kprobe
编译,连接 -- 笔记
utils.DeprecatedIn35 因升级可能取消,该如何办
PHP 的运算符
Example of time complexity calculation
移动app软件测试工具有哪些?第三方软件测评小编分享
fatal error: torch/extension. h: No such file or directory
Openstack theoretical knowledge