PHP 运算符
完整覆盖 PHP 算术、整除 intdiv、赋值、递增递减、比较、逻辑、数组、三元、NULL 合并 ??、太空船 <=> 运算符及优先级结合性,并在 PHP 8.4 逐类实测。
学完这一章,你能够
- 完整覆盖 PHP 算术、整除 intdiv、赋值、递增递减、比较、逻辑、数组、三元、NULL 合并 ??、太空船 <=> 运算符及优先级结合性,并在 PHP 8.4 逐类实测。
算术运算符、按位取反与 intdiv() 整除
PHP 通过丰富的运算符完成赋值与表达式求值,最基础的包括赋值运算符 `=` 与算术加法 `+`。算术与相关一元/拼接运算符涵盖加 `+`、减 `-`、乘 `*`、除 `/`、取模 `%`、取负 `-x`、按二进制位取反 `~x`(补码规则 `~0 = -1`、`~1 = -2`、`~2 = -3`)以及字符串并置 `.`。本站 PHP 8.4.27 实测 `$x = 10; $y = 6;` 得到和 `16`、差 `4`、积 `60`、商保留 6 位 `1.666667`、余数 `4`、取负 `-10`,以及 `'Hi' . 'Ha'` 得到 `'HiHa'`。
PHP 7+ 新增整除函数 `intdiv()`,返回两个整数相除后向零截断的整型商(对正数等价于向下取整)。本站实测 `intdiv(10, 3)` 返回整型 `3`,`intdiv(-7, 2)` 返回 `-3`。
赋值、字符串追加与递增/递减运算符
基本赋值运算符 `=` 将右侧表达式的值赋给左操作数;复合赋值 `+=`、`-=`、`*=`、`/=`、`%=` 与字符串追加赋值 `.=` 则在原变量基础上直接更新。本站实测依次执行赋值与复合运算,精确产出 `[10, 120, 25, 30, 2, 3, 'Hello world!']`。
递增与递减运算符区分前置(先修改再返回)与后置(先返回旧值再修改)。本站实测:`$ix = 10` 执行 `++$ix` 返回 `11` 且变量变为 `11`;`$iy = 10` 执行 `$iy++` 返回 `10` 而变量变为 `11`;`$iz = 5` 执行 `--$iz` 返回 `4`;`$ii = 5` 执行 `$ii--` 返回 `5` 而变量变为 `4`。
比较、逻辑与数组运算符
比较运算符用于比较两个值的大小或相等性,包括松散相等 `==`、严格恒等 `===`、不等 `!=` / `<>`、不恒等 `!==` 以及 `>`、`<`、`>=`、`<=`。本站实测 `100 == '100'` 为 `true`、`100 === '100'` 为 `false`、`5 != 8` 与 `5 <> 8` 均为 `true`、`5 !== '5'` 为 `true`。
逻辑运算符包含 `and`/`&&`(与)、`or`/`||`(或)、`xor`(异或,仅一个为真时为真)和 `!`(非)。数组运算符中,联合运算符 `$x + $y` 会合并键并在键冲突时**保留左侧键值**;数组相等 `==` 只要求键值对相等(不计顺序与严格类型),恒等 `===` 要求键值对、顺序与类型全部一致。本站实测 `['a'=>'red','b'=>'green'] + ['b'=>'blue','c'=>'yellow']` 保留 `'b'=>'green'` 得到 3 元素数组;与调换顺序的 `['b'=>'green','a'=>'red']` 比较时 `==` 为 `true` 而 `===` 为 `false`。
三元、NULL 合并(??)与太空船(<=>)运算符
三元条件运算符 `(expr1) ? (expr2) : (expr3)` 按条件真假返回对应分支;PHP 5.3 起支持省略中间分支的 Elvis 写法 `expr1 ?: expr3`(当 `expr1` 为真返回自身否则返回 `expr3`,但直接读取不存在的数组键在 PHP 8 中会触发未定义键警告)。跨平台换行符常量 `PHP_EOL` 可兼容不同操作系统换行。PHP 7+ 引入的 NULL 合并运算符 `??` 等价于 `isset($a) ? $a : $b`,既不触发未定义键警告,也仅在变量不存在或为 `null` 时回退默认值(保留空字符串 `''` 或 `0`)。本站 PHP 8.4.27 实测:缺失键通过 `??` 零警告返回 `'nobody'`,已有空字符串键通过 `?:` 返回 `'nobody'` 而通过 `??` 保留 `''`。
PHP 7+ 的组合比较符 `<=>`(太空船操作符,语法 `$c = $a <=> $b;`)可统一比较整数、浮点数与字符串:`$a > $b` 返回 `1`,`$a == $b` 返回 `0`,`$a < $b` 返回 `-1`。本站实测整型、浮点与字符串三组对照均精确输出 `[0, -1, 1]`。
运算符优先级与括号显式分组
当表达式包含多个运算符时,优先级从高到低决定结合顺序,同优先级由结合方向(左结合从左到右、右结合从右到左、无结合不可直接连写)决定。`&&`/`||` 的优先级高于赋值 `=`,而 `and`/`or` 的优先级低于 `=`:本站实测 `$a = 3; $b = false; $c = $a or $b;` 先完成 `$c = $a`,故 `$c` 为整型 `3`;而 `$d = $a || $b;` 先求值逻辑或,故 `$d` 为布尔值 `true`。此外需补充 PHP 8.0+ 重要优先级变化:算术 `+`/`-` 现已高于字符串并置 `.`(本站实测 `"sum=" . 1 + 2` 输出 `"sum=3"`),且未加括号的嵌套三元运算符在 PHP 8 已改为编译错误。
在工程代码中应主动使用圆括号 `()` 显式标明运算分组,既避免记忆复杂优先级表带来的隐患,也显著提升可读性。本站实测 `1 + 2 * 3` 得 `7`,加上括号 `(1 + 2) * 3` 得 `9`。
PHP 算术与相关一元/拼接运算符
| 运算符 | 名称 | 说明 | 示例 | 实测结果 |
|---|---|---|---|---|
| x + y | 加 | 计算 x 与 y 之和 | 10 + 6 | 16 |
| x - y | 减 | 计算 x 减去 y 之差 | 10 - 6 | 4 |
| x * y | 乘 | 计算 x 与 y 之积 | 10 * 6 | 60 |
| x / y | 除 | 计算 x 除以 y 之商 | round(10 / 6, 6) | 1.666667 |
| x % y | 模(余数) | 计算 x 除以 y 的整数余数 | 10 % 6 | 4 |
| -x | 取负 | 取操作数的相反数 | -10 | -10 |
| ~x | 按位取反 | 对整型按二进制补码逐位取反(~0=-1, ~1=-2) | ~2 | -3 |
| a . b | 并置 | 连接两个字符串 | 'Hi' . 'Ha' | 'HiHa' |
PHP 赋值运算符
| 运算符 | 等价形式 | 说明 |
|---|---|---|
| x = y | x = y | 将右侧表达式的值赋给左操作数 |
| x += y | x = x + y | 加法复合赋值 |
| x -= y | x = x - y | 减法复合赋值 |
| x *= y | x = x * y | 乘法复合赋值 |
| x /= y | x = x / y | 除法复合赋值 |
| x %= y | x = x % y | 取模复合赋值 |
| a .= b | a = a . b | 字符串追加连接赋值 |
PHP 递增与递减运算符
| 运算符 | 名称 | 说明 |
|---|---|---|
| ++$x | 预递增 | 先将 x 加 1,再返回新值 |
| $x++ | 后递增 | 先返回当前值,再将 x 加 1 |
| --$x | 预递减 | 先将 x 减 1,再返回新值 |
| $x-- | 后递减 | 先返回当前值,再将 x 减 1 |
PHP 比较运算符
| 运算符 | 名称 | 说明 | 实测示例 |
|---|---|---|---|
| x == y | 松散等于 | 隐式类型转换后值相等返回 true | 100 == '100' → true |
| x === y | 严格恒等 | 值与类型完全一致才返回 true | 100 === '100' → false |
| x != y | 松散不等 | 隐式转换后值不等返回 true | 5 != 8 → true |
| x <> y | 松散不等 | 与 != 等价,值不等返回 true | 5 <> 8 → true |
| x !== y | 严格不恒等 | 值不等或类型不同即返回 true | 5 !== '5' → true |
| x > y | 大于 | 左操作数大于右操作数返回 true | 50 > 90 → false |
| x < y | 小于 | 左操作数小于右操作数返回 true | 50 < 90 → true |
| x >= y | 大于等于 | 左操作数大于或等于右操作数返回 true | 5 >= 8 → false |
| x <= y | 小于等于 | 左操作数小于或等于右操作数返回 true | 5 <= 8 → true |
PHP 逻辑运算符
| 运算符 | 名称 | 说明 | 实测示例(x=6, y=3) |
|---|---|---|---|
| x and y | 逻辑与(低优先级) | 两者皆真返回 true,优先级低于 = | (6 < 10 and 3 > 1) → true |
| x or y | 逻辑或(低优先级) | 至少一真返回 true,优先级低于 = | (6 == 6 or 3 == 5) → true |
| x xor y | 逻辑异或 | 有且仅有一个为真返回 true | (6 == 6 xor 3 == 3) → false |
| x && y | 逻辑与(高优先级) | 两者皆真返回 true,优先级高于 = | (6 < 10 && 3 > 1) → true |
| x || y | 逻辑或(高优先级) | 至少一真返回 true,优先级高于 = | (6 == 5 || 3 == 5) → false |
| !x | 逻辑非 | 对布尔真值取反 | !(6 == 3) → true |
PHP 数组运算符
| 运算符 | 名称 | 说明 |
|---|---|---|
| x + y | 联合 | 合并两个数组,键名冲突时保留左侧数组的值 |
| x == y | 相等 | 两数组拥有相同的键值对(不要求顺序和严格类型)返回 true |
| x === y | 恒等 | 键值对、排列顺序与类型全部一致才返回 true |
| x != y | 不相等 | 两数组不满足相等条件时返回 true |
| x <> y | 不相等 | 与 != 等价的数组不等判断 |
| x !== y | 不恒等 | 键值对、顺序或类型任意不同即返回 true |
PHP 运算符优先级(由高到低)与结合方向
| 结合方向 | 运算符 | 类别与 PHP 8 补充说明 |
|---|---|---|
| 无 | clone new | 对象克隆与实例化 |
| 左 | [ | 数组下标访问(早期对应 array()) |
| 右 | ++ -- ~ (int) (float) (string) (array) (object) (bool) @ | 递增递减、按位取反、强制类型转换与错误抑制 |
| 无 | instanceof | 对象类型检查 |
| 右 | ! | 逻辑非 |
| 左 | * / % | 乘、除与取模算术运算 |
| 左 | + - . | 加减与并置(PHP 8.0 起 `+`/`-` 优先级严格高于 `.`,实测 `"sum=" . 1 + 2 === "sum=3"`) |
| 左 | << >> | 二进制左移与右移位运算 |
| 无 | == != === !== <> | 相等与不等比较(以及 PHP 7+ `<=>`) |
| 左 | & | 按位与及引用 |
| 左 | ^ | 按位异或 |
| 左 | | | 按位或 |
| 左 | && | 高优先级逻辑与(高于赋值 `=`) |
| 左 | || | 高优先级逻辑或(高于赋值 `=`) |
| 左(PHP 8 改为无结合) | ? : | 三元条件运算符;PHP 8.0 起嵌套三元必须显式加括号 |
| 右 | = += -= *= /= .= %= &= |= ^= <<= >>= => | 基本与复合赋值及数组键值映射 |
| 左 | and | 低优先级逻辑与(低于赋值 `=`) |
| 左 | xor | 低优先级逻辑异或 |
| 左 | or | 低优先级逻辑或(低于赋值 `=`) |
| 左 | , | 参数列表与多表达式分隔符 |
实测 PHP 8.4 全部运算符类别、?? 与 <=> 及优先级与括号分组行为
<?php
declare(strict_types=1);
$cases = [];
// Case 1: Arithmetic, unary negation, bitwise NOT (~), string concat (.), and intdiv()
$x = 10;
$y = 6;
$c1Actual = [
'add' => $x + $y,
'sub' => $x - $y,
'mul' => $x * $y,
'div_round6' => round($x / $y, 6),
'mod' => $x % $y,
'neg' => -$x,
'bitnot_0' => ~0,
'bitnot_1' => ~1,
'bitnot_2' => ~2,
'concat' => 'Hi' . 'Ha',
'intdiv_10_3' => intdiv(10, 3),
'intdiv_neg7_2' => intdiv(-7, 2),
];
$c1Expected = [
'add' => 16,
'sub' => 4,
'mul' => 60,
'div_round6' => 1.666667,
'mod' => 4,
'neg' => -10,
'bitnot_0' => -1,
'bitnot_1' => -2,
'bitnot_2' => -3,
'concat' => 'HiHa',
'intdiv_10_3' => 3,
'intdiv_neg7_2' => -3,
];
$cases[] = [
'name' => 'arithmetic_bitwise_and_intdiv',
'passed' => $c1Actual === $c1Expected,
'expected' => $c1Expected,
'actual' => $c1Actual,
];
// Case 2: Assignment operators (=, +=, -=, *=, /=, %=, .=) and pre/post increment & decrement
$a = 10;
$b = 20; $b += 100;
$c = 50; $c -= 25;
$d = 5; $d *= 6;
$e = 10; $e /= 5;
$f = 15; $f %= 4;
$s = 'Hello'; $s .= ' world!';
$ix = 10; $preInc = ++$ix;
$iy = 10; $postInc = $iy++;
$iz = 5; $preDec = --$iz;
$ii = 5; $postDec = $ii--;
$c2Actual = [
'assign_vals' => [$a, $b, $c, $d, $e, $f, $s],
'pre_inc' => [$preInc, $ix],
'post_inc' => [$postInc, $iy],
'pre_dec' => [$preDec, $iz],
'post_dec' => [$postDec, $ii],
];
$c2Expected = [
'assign_vals' => [10, 120, 25, 30, 2, 3, 'Hello world!'],
'pre_inc' => [11, 11],
'post_inc' => [10, 11],
'pre_dec' => [4, 4],
'post_dec' => [5, 4],
];
$cases[] = [
'name' => 'assignment_string_and_incdec',
'passed' => $c2Actual === $c2Expected,
'expected' => $c2Expected,
'actual' => $c2Actual,
];
// Case 3: Comparison, Logical (and/or/xor/&&/||/!), and Array (+, ==, ===, !=, <>, !==) operators
$arr1 = ['a' => 'red', 'b' => 'green'];
$arr2 = ['b' => 'blue', 'c' => 'yellow'];
$arrSameOrderDiff = ['b' => 'green', 'a' => 'red'];
$lx = 6;
$ly = 3;
$c3Actual = [
'cmp_loose' => (100 == '100'),
'cmp_strict' => (100 === '100'),
'cmp_neq_bang' => (5 != 8),
'cmp_neq_angle' => (5 <> 8),
'cmp_not_ident' => (5 !== '5'),
'cmp_gt_lt_ge_le' => [50 > 90, 50 < 90, 5 >= 8, 5 <= 8],
'logic' => [
($lx < 10 and $ly > 1),
($lx == 6 or $ly == 5),
($lx == 6 xor $ly == 3),
($lx < 10 && $ly > 1),
($lx == 5 || $ly == 5),
!($lx == $ly),
],
'array_union_left_wins' => ($arr1 + $arr2),
'array_eq_diff_order' => ($arr1 == $arrSameOrderDiff),
'array_ident_diff_order' => ($arr1 === $arrSameOrderDiff),
'array_neq_ops' => [($arr1 != $arr2), ($arr1 <> $arr2), ($arr1 !== $arrSameOrderDiff)],
];
$c3Expected = [
'cmp_loose' => true,
'cmp_strict' => false,
'cmp_neq_bang' => true,
'cmp_neq_angle' => true,
'cmp_not_ident' => true,
'cmp_gt_lt_ge_le' => [false, true, false, true],
'logic' => [true, true, false, true, false, true],
'array_union_left_wins' => ['a' => 'red', 'b' => 'green', 'c' => 'yellow'],
'array_eq_diff_order' => true,
'array_ident_diff_order' => false,
'array_neq_ops' => [true, true, true],
];
$cases[] = [
'name' => 'comparison_logical_and_array_ops',
'passed' => $c3Actual === $c3Expected,
'expected' => $c3Expected,
'actual' => $c3Actual,
];
// Case 4: Ternary (?:), Elvis, Null Coalescing (??), PHP_EOL, and Spaceship (<=>)
$query = ['empty_user' => ''];
$warnings = 0;
set_error_handler(static function () use (&$warnings): bool {
$warnings++;
return true;
});
$ternaryUser = isset($query['user']) ? $query['user'] : 'nobody';
$elvisUser = $query['empty_user'] ?: 'nobody';
$coalesceMissing = $query['user'] ?? 'nobody';
$coalesceEmpty = $query['empty_user'] ?? 'nobody';
restore_error_handler();
$c4Actual = [
'ternary_missing' => $ternaryUser,
'elvis_empty_string' => $elvisUser,
'coalesce_missing' => $coalesceMissing,
'coalesce_keeps_empty_str' => $coalesceEmpty,
'zero_warnings' => $warnings === 0,
'eol_non_empty' => PHP_EOL !== '',
'spaceship_int' => [1 <=> 1, 1 <=> 2, 2 <=> 1],
'spaceship_float' => [1.5 <=> 1.5, 1.5 <=> 2.5, 2.5 <=> 1.5],
'spaceship_str' => ['a' <=> 'a', 'a' <=> 'b', 'b' <=> 'a'],
];
$c4Expected = [
'ternary_missing' => 'nobody',
'elvis_empty_string' => 'nobody',
'coalesce_missing' => 'nobody',
'coalesce_keeps_empty_str' => '',
'zero_warnings' => true,
'eol_non_empty' => true,
'spaceship_int' => [0, -1, 1],
'spaceship_float' => [0, -1, 1],
'spaceship_str' => [0, -1, 1],
];
$cases[] = [
'name' => 'ternary_null_coalesce_and_spaceship',
'passed' => $c4Actual === $c4Expected,
'expected' => $c4Expected,
'actual' => $c4Actual,
];
// Case 5: Operator precedence (|| vs or with =, parentheses, and PHP 8 + before .)
$pa = 3;
$pb = false;
$pc = $pa or $pb;
$pd = $pa || $pb;
$noParen = 1 + 2 * 3;
$withParen = (1 + 2) * 3;
$php8AddBeforeConcat = "sum=" . 1 + 2;
$c5Actual = [
'assign_or_val' => $pc,
'assign_or_type' => gettype($pc),
'assign_pipe_val' => $pd,
'assign_pipe_type' => gettype($pd),
'no_paren' => $noParen,
'with_paren' => $withParen,
'php8_add_before_concat' => $php8AddBeforeConcat,
];
$c5Expected = [
'assign_or_val' => 3,
'assign_or_type' => 'integer',
'assign_pipe_val' => true,
'assign_pipe_type' => 'boolean',
'no_paren' => 7,
'with_paren' => 9,
'php8_add_before_concat' => 'sum=3',
];
$cases[] = [
'name' => 'precedence_and_parentheses',
'passed' => $c5Actual === $c5Expected,
'expected' => $c5Expected,
'actual' => $c5Actual,
];
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
- 在 PHP 8.4.27 中验证算术/位反/intdiv、复合赋值与递增递减、比较/逻辑/数组联合、三元/??/<=> 以及 || vs or 与 PHP 8 `+` 高于 `.` 的优先级。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
当前源码 SHA256:d1bf232ad74042bdc17c1cf61a4925fb6f10d97b2ca6f841b02afb89dc7bdcf6
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、PHP 8.4 本地 CLI 环境。
ZIP SHA256:243ae11b1868334761a38d6d4acfde3a25d0ae7b686ad282768b79ecc6c98f3f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 PHP 8.4 中,`$c = 3 or false;` 与 `$d = 3 || false;` 的结果有何不同?在读取可选数组键时,`??` 相比 `?:` 有什么优势?
展开参考解答
因为 `=` 优先级高于 `or` 但低于 `||`,前者等价于 `($c = 3) or false` 得整型 `3`,后者等价于 `$d = (3 || false)` 得布尔值 `true`;`??` 在键不存在时不会发出 `E_WARNING` 且仅在未定义或为 `null` 时回退,不会误把 `''` 或 `0` 替换掉。