略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 算术运算符

2024-04-24

算术运算符

还记得学校里学到的基本数学知识吗?就和它们一样。

算术运算符
例子 名称 结果
+$a 标识 根据情况将 $a 转化为 intfloat
-$a 取反 $a 的负值。
$a + $b 加法 $a$b 的和。
$a - $b 减法 $a$b 的差。
$a * $b 乘法 $a$b 的积。
$a / $b 除法 $a 除以 $b 的商。
$a % $b 取模 $a 除以 $b 的余数。
$a ** $b 求幂 $a$b次方的值。

除法运算符总是返回浮点数。只有在下列情况例外:两个操作数都是整数(或字符串转换成的整数)并且正好能整除,这时它返回一个整数。 整数除法可参考 intdiv()

取模运算符的操作数在运算之前都会转换成 int 。 浮点数取模可参考 fmod()

取模运算符 % 的结果和被除数的符号(正负号)相同。即 $a % $b 的结果和 $a 的符号相同。例如:

<?php

echo (3)."\n";           // 打印 2
echo (% -3)."\n";          // 打印 2
echo (-3)."\n";          // 打印 -2
echo (-% -3)."\n";         // 打印 -2

?>

参见

add a noteadd a note

User Contributed Notes 2 notes

up
-1
Zeomni
1 month ago
With PHP 8.1 and more, be carefull to the modulo "%"

Both argument must be some integer or a float without floating part.

Bad Example:
<?php
12.5
% 4.5
?>

You will enjoy a :
Deprecated: Implicit conversion from float 12.5 to int loses precision in ... filename
Deprecated: Implicit conversion from float 5.4 to int loses precision in ... filename

A fix, cast your int :
<?php

(int) 12.5 % (int)4.5
up
-64
r dot shipelov at tradesoft dot ru
10 months ago
Regarding the operation of division with remainder (%) - it differs from the one accepted in mathematics, since it is looking for "refusal" and not "remainder" - a feature of the idiv implementation in 8086

官方地址:https://www.php.net/manual/en/language.operators.arithmetic.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3