PHP 的比较运算与逻辑运算
好的,以下是您提供的 PHP 相关知识的总结和解释:
1. 类型比较
- PHP4:对象之间的比较方式与数组相同。
- PHP5:对象类型间的
==比较为true的前提是它们属于同一个类的实例(并且还要进行属性的比较)。===比较更加严格,要求对象是同一个实例。
2. empty() 函数
- 在 PHP4 中,不包括任何成员变量的对象被
empty()判断为true。 - 字符串偏移 offset 取字符的
empty()判定:取对应 offset 的字符进行判断。在 PHP5.4 之前,使用索引从字符串中取字符时会先将索引进行取整,因此左侧不包含数字的字符串都被转换成0。PHP5.4 之后,不再对非整形格式的字符串索引进行取整。
3. 跨类型数据比较
- 不要在 PHP 的跨类型数据比较中使用“传递性”。例如:
这并不能说明$a == $b; // true $b == $c; // true$a == $c为true。
4. 数组的比较方法
function standard_array_compare($op1, $op2) { if (count($op1) < count($op2)) { return -1; // $op1 < $op2 } elseif (count($op1) > count($op2)) { return 1; // $op1 > $op2 } foreach ($op1 as $key => $val) { if (!array_key_exists($key, $op2)) { return null; // uncomparable } elseif ($val < $op2[$key]) { return -1; } elseif ($val > $op2[$key]) { return 1; } } return 0; // $op1 == $op2 } 5. 三元运算符 ?:
- PHP 的三元运算符是左结合的。例如:
$arg = 'T'; $vehicle = ( ($arg == 'B') ? 'bus' : ($arg == 'A') ? 'airplane' : ($arg == 'T') ? 'train' : ($arg == 'C') ? 'car' : ($arg == 'H') ? 'horse' : 'feet' ); echo $vehicle; // horse
6. switch 比较
- 在 PHP 中,
switch的比较不是===而是==。
7. 标准比较运算符
// 数组是用标准比较运算符这样比较的 function standard_array_compare($op1, $op2) { if (count($op1) < count($op2)) { return -1; // $op1 < $op2 } elseif (count($op1) > count($op2)) { return 1; // $op1 > $op2 } foreach ($op1 as $key => $val) { if (!array_key_exists($key, $op2)) { return null; // uncomparable } elseif ($val < $op2[$key]) { return -1; } elseif ($val > $op2[$key]) { return 1; } } return 0; // $op1 == $op2 } 这些是 PHP 中一些重要的概念和规则,希望对您有所帮助。如果您有任何具体的问题或需要进一步的解释,请随时提问。