蓝色天空.知识 · 实践 · 创造
我的收藏
PHP 教程目录 95章
课程介绍
PHP / LEARN BY DOING

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 + 616
x - y减计算 x 减去 y 之差10 - 64
x * y乘计算 x 与 y 之积10 * 660
x / y除计算 x 除以 y 之商round(10 / 6, 6)1.666667
x % y模(余数)计算 x 除以 y 的整数余数10 % 64
-x取负取操作数的相反数-10-10
~x按位取反对整型按二进制补码逐位取反(~0=-1, ~1=-2)~2-3
a . b并置连接两个字符串'Hi' . 'Ha''HiHa'

PHP 赋值运算符

运算符等价形式说明
x = yx = y将右侧表达式的值赋给左操作数
x += yx = x + y加法复合赋值
x -= yx = x - y减法复合赋值
x *= yx = x * y乘法复合赋值
x /= yx = x / y除法复合赋值
x %= yx = x % y取模复合赋值
a .= ba = a . b字符串追加连接赋值

PHP 递增与递减运算符

运算符名称说明
++$x预递增先将 x 加 1,再返回新值
$x++后递增先返回当前值,再将 x 加 1
--$x预递减先将 x 减 1,再返回新值
$x--后递减先返回当前值,再将 x 减 1

PHP 比较运算符

运算符名称说明实测示例
x == y松散等于隐式类型转换后值相等返回 true100 == '100' → true
x === y严格恒等值与类型完全一致才返回 true100 === '100' → false
x != y松散不等隐式转换后值不等返回 true5 != 8 → true
x <> y松散不等与 != 等价,值不等返回 true5 <> 8 → true
x !== y严格不恒等值不等或类型不同即返回 true5 !== '5' → true
x > y大于左操作数大于右操作数返回 true50 > 90 → false
x < y小于左操作数小于右操作数返回 true50 < 90 → true
x >= y大于等于左操作数大于或等于右操作数返回 true5 >= 8 → false
x <= y小于等于左操作数小于或等于右操作数返回 true5 <= 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 全部运算符类别、?? 与 <=> 及优先级与括号分组行为

含完整源码 · 203 行
展开查看收起
php
<?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 `+` 高于 `.` 的优先级。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1232.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1278.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为 `=` 优先级高于 `or` 但低于 `||`,前者等价于 `($c = 3) or false` 得整型 `3`,后者等价于 `$d = (3 || false)` 得布尔值 `true`;`??` 在键不存在时不会发出 `E_WARNING` 且仅在未定义或为 `null` 时回退,不会误把 `''` 或 `0` 替换掉。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习