PHP中的运算符使用示例详细指南

来自:网络
时间:2022-12-25
阅读:
目录

正文

一旦你有了一些变量,你就可以对它们进行运算:

$base = 20;
$height = 10;
$area = $base * $height;

我用来将base与height相乘的* ,就是乘法运算。

我们有相当多的运算符,让我们对主要的运算符做一个简单的总结。

首先,这里是算术运算符。+,-,*,/ (除法),% (余数)和** (指数)。

我们有赋值运算符= ,我们已经用它来给一个变量赋值了。

接下来我们有比较运算符,如<,>,<=,>= 。这些运算符的工作原理与数学中的一样:

2 < 1; //false
1 <= 1; // true
1 <= 2; // true

== 如果两个操作数相等,返回真。

=== 如果两个操作数相同,则返回 "真"。

这有什么区别?

随着经验的积累,你会发现的,但举例来说:

1 == '1'; //true
1 === '1'; //false

我们还有!= 来检测操作数是否不相等:

1 != 1; //false
1 != '1'; //false
1 != 2; //true
//hint: <> works in the same way as !=, 1 <> 1

!== ,来检测操作数是否不相同:

1 !== 1; //false
1 !== '1'; //true

逻辑运算符对布尔值起作用

// Logical AND with && or "and"
true && true; //true
true && false; //false
false && true; //false
false && false; //false
true and true; //true
true and false; //false
false and true; //false
false and false; //false
// Logical OR with || or "or"
true || true; // true
true || false //true
false || true //true
false || false //false
true or true; // true
true or false //true
false or true //true
false or false //false
// Logical XOR (one of the two is true, but not both)
true xor true; // false
true xor false //true
false xor true //true
false xor false //false

not运算符:

$test = true
!$test //false

我在这里使用了布尔值truefalse ,但在实践中,你会使用评估为真或假的表达式,比如说:

1 > 2 || 2 > 1; //true
1 !== 2 && 2 > 2; //false

上面列出的所有运算符都是二进制的,意味着它们涉及到两个操作数。

2个单数运算符

PHP也有2个单数运算符:++--

$age = 20;
$age++;
//age is now 21
$age--;
//age is now 20

以上就是PHP中的运算符使用示例详细指南的详细内容,更多关于PHP中运算符的资料请关注其它相关文章!

返回顶部
顶部