Home Backend Development PHP Tutorial PHP 8: PHP的运算符

PHP 8: PHP的运算符

Jun 23, 2016 pm 02:35 PM

本章将介绍PHP的运算符。
运算符这个问题在每种语言里都有,因为我们已经熟悉了编程语言里的一种或是多种,所以只需要了解一下就行了。
概括一下吧。
PHP运算符有很多种,看样子要比C/C++,C#等语言多多了。分别是:
算术运算符 赋值运算符 位运算符 比较运算符 错误控制运算符 执行运算符 递增/递减运算符 逻辑运算符 字符串运算符 数组运算符 类型运算符 这也是蛮多的,五花八门的。

算术运算符

例子

名称

结果

-$a

取反

$a 的负值。

$a + $b

加法

$a 和 $b 的和。

$a - $b

减法

$a 和 $b 的差。

$a * $b

乘法

$a 和 $b 的积。

$a / $b

除法

$a 除以 $b 的商。

$a % $b

取模

$a 除以 $b 的余数。

位运算符

例子

名称

结果

$a & $b

And(按位与)

将把 $a 和 $b 中都为 1 的位设为 1。

$a | $b

Or(按位或)

将把 $a 或者 $b 中为 1 的位设为 1。

$a ^ $b

Xor(按位异或)

将把 $a 和 $b 中不同的位设为 1。

~ $a

Not(按位非)

将 $a 中为 0 的位设为 1,反之亦然。

$a

Shift left(左移)

将 $a 中的位向左移动 $b 次(每一次移动都表示“乘以 2” )。

$a >> $b

Shift right(右移)

将 $a 中的位向右移动 $b 次(每一次移动都表示“除以 2” )。

比较运算符

例子

名称

结果

$a == $b

等于

TRUE,如果 $a 等于 $b。

$a === $b

全等

TRUE,如果 $a 等于 $b,并且它们的类型也相同。(PHP 4 引进)

$a != $b

不等

TRUE,如果 $a 不等于 $b。

$a $b

不等

TRUE,如果 $a 不等于 $b。

$a !== $b

非全等

TRUE,如果 $a 不等于 $b,或者它们的类型不同。(PHP 4 引进)

$a

小与

TRUE,如果 $a 严格小于 $b。

$a > $b

大于

TRUE,如果 $a 严格 $b。

$a

小于等于

TRUE,如果 $a 小于或者等于 $b。

$a >= $b

大于等于

TRUE,如果 $a 大于或者等于 $b。

递增/递减运算符

例子

名称

效果

++$a

前加

$a 的值加一,然后返回 $a。

$a++

后加

返回 $a,然后将 $a 的值加一。

--$a

前减

$a 的值减一, 然后返回 $a。

$a--

后减

返回 $a,然后将 $a 的值减一。

逻辑运算符

例子

名称

结果

$a and $b

And(逻辑与)

TRUE,如果 $a 与 $b 都为 TRUE。

$a or $b

Or(逻辑或)

TRUE,如果 $a 或 $b 任一为 TRUE。

$a xor $b

Xor(逻辑异或)

TRUE,如果 $a 或 $b 任一为 TRUE,但不同时是。

! $a

Not(逻辑非)

TRUE,如果 $a 不为 TRUE。

$a && $b

And(逻辑与)

TRUE,如果 $a 与 $b 都为 TRUE。

$a || $b

Or(逻辑或)

TRUE,如果 $a 或 $b 任一为 TRUE。

数组运算符

例子

名称

结果

$a + $b

联合

$a 和 $b 的联合。

$a == $b

相等

如果 $a 和 $b 具有相同的键/值对则为 TRUE。

$a === $b

全等

如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE。

$a != $b

不等

如果 $a 不等于 $b 则为 TRUE。

$a $b

不等

如果 $a 不等于 $b 则为 TRUE。

$a !== $b

不全等

如果 $a 不全等于 $b 则为 TRUE。

当然还有几种类型的没有列出,将在后面描述。我们先看看列出的吧。
如果没有对上面的运算符做特殊说明,那么说明它们和C#里的相似。
首先看看位运算里的左移(>),其实没有什么不同,只是符号不一样而已。 看看比较运算法里的“==”,“===”,这两个比较有意思,它们有什么区别呢?             看看一下代码:             

 1  php
 2  var_dump ( 0   ==   " a " );  //  0 == 0 -> true
 3  var_dump ( " 1 "   ==   " 01 " );  //  1 == 1 -> true
 4 
 5  switch  ( " a " ) {
 6  case   0 :
 7      echo   " 0 " ;
 8      break ;
 9  case   " a " :   //  never reached because "a" is already matched with 0
10      echo   " a " ;
11      break ;
12  }

         看第2行,为什么0会等于“a”呢?奇怪了。之所以会相等,是因为在PHP里,如果整型和字符串比较时,字符串会自动的转化为数值。这里就会有一个问题:字符串转化为数值的原则是什么?原则是

                 1)如果包括“.”,“e”或“E”其中任何一个字符的话,字符串被当作 float 来求值。否则就被当作整数。

                2)该值由字符串最前面的部分决定。如果字符串以合法的数字数据开始,就用该数字作为其值,否则其值为 0(零)。合法数字数据由可选的正负号开始,后面跟着一个或多个数字(可选地包括十进制分数),后面跟着可选的指数。指数是一个“e”或者“E”后面跟着一个或多个数字。例如:

 1  php
 2  $var   =   1   +   " 10.5 " ;                
 3  echo   " 1 + \ " 10.5 \ " = " . $var . " ; type: " . gettype ( $var ) . "
" ;
 4  $var   =   1   +   " -1.3e3 " ;              
 5  echo   " 1 + \ " - 1.3e3 \ " = " . $var . " ; type: " . gettype ( $var ) . "
" ;
 6  $var   =   1   +   " bob-1.3e3 " ;          
 7  echo   " 1 + \ " bob - 1.3e3 \ " = " . $var . " ; type: " . gettype ( $var ) . "
" ;
 8  $var   =   1   +   " bob3 " ;                
 9  echo   " 1 + \ " bob3\ " = " . $var . " ; type: " . gettype ( $var ) . "
" ;
10  $var   =   1   +   " 10 beatiful birds " ;      
11  echo   " 1 + \ " 10  beatiful birds\ " = " . $var . " ; type: " . gettype ( $var ) . "
" ;
12  $var =   4   +   " 10.2 Little Apple " ; 
13  echo   " 4 + \ " 10.2  Little Apple\ " = " . $var . " ; type: " . gettype ( $var ) . "
" ;
14  $var   =   " 10.0 pigs  "   +   1 ;          
15  echo   " \ " 10.0  pigs \ "  + 1= " . $var . " ; type: " . gettype ( $var ) . "
" ;
16  $var   =   " 10.0 pigs  "   +   1.0 ;        
17  echo    " \ " 10.0  pigs \ "  + 1.0= " . $var . " ; type: " . gettype ( $var ) . "
" ;
18  ?>  
19 

输出的结果是:

1   +   " 10.5 " = 11.5 ; type : double
1   +   " -1.3e3 " =- 1299 ; type : double
1   +   " bob-1.3e3 " = 1 ; type : integer
1   +   " bob3 " = 1 ; type : integer
1   +   " 10 beatiful birds " = 11 ; type : integer
4   +   " 10.2 Little Apple " = 14.2 ; type : double
" 10.0 pigs  "   +   1 = 11 ; type : double
" 10.0 pigs  "   +   1.0 = 11 ; type : double

现在明白是怎么回事了吧。为什么“a”为0就是这个道理。
既然如此,还有一个“===”,3个等于符号,它表示不仅最后转化的数值相等,而且类型也应该相等。看看下面的代码:

1  php
2    var_dump ( 0   ===   " a " );  //  0 === 0 -> false
3    echo   '
' ;
4    var_dump ( 0   ===   " 00 " );  //  0 === "00" -> false
5    echo   '
' ;
6    var_dump ( 0   ===   0 );  //  0 === 0 -> true
7    echo   '
' ;
8  ?>

输出结果为:

bool( false )
bool( false )
bool( true ) 

第6行之所以为true,是因为它们不仅数值相等,而且类型也一样。
   3)看看逻辑运算,“或”和“与”居然有2种写法,如果你使用C/C++,C#,Java等语言的话,就用“&&"或”||"吧。如果你是VB的话,就用and,和or。当然你也可以2种都用。它们有什么区别呢?优先级的不同而已。”&&“与"||"比”and“和”or“优先级要高。
  4).PHP多了一个数组运算符。有了上面的解释,相信它们不是很难了。

赋值运算符            和C#语言一样,也是利用”=“,也是利用二元符号赋值。例如:

php
  $a = ' hello ' ;  // $a是hello。
  $a += 1 ;       // $a是1,二元赋值符
  $b = ' world ' ;
  $c = ' hello ' ;
  $c .= $b ; // $c是"hello world"
?>


错误执行运算符        PHP 支持一个错误控制运算符:@。当将其放置在一个 PHP 表达式之前,该表达式可能产生的任何错误信息都被忽略掉。

     如果激活了 track_errors 特性,表达式所产生的任何错误信息都被存放在变量 $php_errormsg 中。此变量在每次出错时都会被覆盖,所以如果想用它的话就要尽早检查。例如:

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.

?>  

 

执行运算符        PHP 支持一个执行运算符:反引号(``)。注意这不是单引号!PHP 将尝试将反引号中的内容作为外壳命令来执行,并将其输出信息返回(例如,可以赋给一个变量而不是简单地丢弃到标准输出)。使用反引号运算符“`”的效果与函数 shell_exec() 相同。反引号位于键盘的”~“键那里。例如:

1  php
2    $out = ` dir  c : `;
3    echo   '

 ' . $out . ' 
Copy after login
' ;
4  ?> 结果为:

 Volume in drive C has no label .
 Volume Serial  Number  is A019 - 7D77

 Directory of C : \

02 / 24 / 2006    10 : 21  PM  Downloads
02 / 24 / 2006   10 : 09  PM Kingsoft Temp Download
05 / 13 / 2006   07 : 07  PM  220  cmd . txt
02 / 13 / 2006   11 : 40  PM WINDOWS
02 / 13 / 2006   11 : 47  PM Documents and Settings
02 / 13 / 2006   11 : 57  PM Program Files
06 / 24 / 2006   11 : 01  PM  482 , 933  nfzmLog . log
05 / 11 / 2006   10 : 28  PM  Inetpub
05 / 13 / 2006   07 : 07  PM  4  response . txt
07 / 29 / 2006   05 : 56  PM  0  Rec . pcm
06 / 24 / 2006   09 : 05  PM nf
07 / 29 / 2006   05 : 56  PM  0  WriteAudrv . wav
07 / 04 / 2006   08 : 52  PM dwnSetup
07 / 08 / 2006   09 : 28  AM TEMP
02 / 14 / 2006   12 : 15  AM NVIDIA
5   File (s)  483 , 157  bytes  10   Dir (s)  2 , 116 , 558 , 848  bytes free 



递增/递减运算符

PHP 支持 C 风格的前/后递增与递减运算符。

注: 递增/递减运算符不影响布尔值。递减 NULL 值也没有效果,但是递增 NULL 的结果是 1。

 递增/递减运算符

例子 名称 效果
++$a 前加 $a 的值加一,然后返回 $a。
$a++ 后加 返回 $a,然后将 $a 的值加一。
--$a 前减 $a 的值减一, 然后返回 $a。
$a-- 后减 返回 $a,然后将 $a 的值减
类型运算符

PHP 有一个类型运算符:instanceof。instanceof 用来测定一个给定的对象是否来自指定的对象类。

instanceof 运算符是 PHP 5 引进的。在此之前用 is_a(),但是 is_a() 已经过时了,最好用 instanceof。

          C#里是is,而Java是instanceof,和PHP一样。例如:

 1  php
 2  class  A { }
 3  class  B { }
 4 
 5  $thing   =   new  A;
 6 
 7  if  ( $thing  instanceof A) {
 8       echo   ' A ' ;
 9  }
10  if  ( $thing  instanceof B) {
11       echo   ' B ' ;
12  }
13  ?>


字符运算符 有两个字符串运算符。第一个是连接运算符(“.”),它返回其左右参数连接后的字符串。第二个是连接赋值运算符(“.=”),它将右边参数附加到左边的参数后。这些在前面已经见到,就不举例了。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles