32. PHP 比较运算符

来源:互联网 发布:linux shell 编辑:程序博客网 时间:2024/06/05 09:09

比较运算符


比较运算符,如同它们名称所暗示的,允许对两个值进行比较。还可以参考 PHP 类型比较表看不同类型相互比较的例子。
这里写图片描述
如果比较一个数字和字符串或者比较涉及到数字内容的字符串,则字符串会被转换为数值并且比较按照数值来进行。此规则也适用于 switch 语句。当用 === 或 !== 进行比较时则不进行类型转换,因为此时类型和数值都要比对。

<?phpvar_dump(0 == "a"); // 0 == 0 -> truevar_dump("1" == "01"); // 1 == 1 -> truevar_dump("10" == "1e1"); // 10 == 10 -> truevar_dump(100 == "1e2"); // 100 == 100 -> trueswitch ("a") {case 0:    echo "0";    break;case "a": // never reached because "a" is already matched with 0    echo "a";    break;}?> 

对于多种类型,比较运算符根据下表比较(按顺序)。
这里写图片描述
Example #1 标准数组比较代码

<?php// 数组是用标准比较运算符这样比较的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}?> 
Warning 比较浮点数 由于浮点数 float 的内部表达方式,不应比较两个浮点数是否相等。 更多信息参见 float

三元运算符


另一个条件运算符是”?:”(或三元)运算符 。

Example #2 赋默认值

<?php // Example usage for: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // The above is identical to this if/else statement if (empty($_POST['action'])) {     $action = 'default'; } else {     $action = $_POST['action']; } ?> 

表达式 (expr1) ? (expr2) : (expr3) 在 expr1 求值为 TRUE 时的值为 expr2,在 expr1 求值为 FALSE 时的值为 expr3。

自 PHP 5.3 起,可以省略三元运算符中间那部分。表达式 expr1 ?: expr3 在 expr1 求值为 TRUE 时返回 expr1,否则返回 expr3。

Note: 注意三元运算符是个语句,因此其求值不是变量,而是语句的结果。如果想通过引用返回一个变量这点就很重要。在一个通过引用返回的函数中语句 return $var == 42 ? $a : $b; 将不起作用,以后的 PHP 版本会为此发出一条警告。

Note:

建议避免将三元运算符堆积在一起使用。当在一条语句中使用多个三元运算符时会造成 PHP 运算结果不清晰:

Example #3 不清晰的三元运算符行为

<?php// 乍看起来下面的输出是 'true'echo (true?'true':false?'t':'f');// 然而,上面语句的实际输出是't',因为三元运算符是从左往右计算的// 下面是与上面等价的语句,但更清晰echo ((true ? 'true' : 'false') ? 't' : 'f');// here, you can see that the first expression is evaluated to 'true', which// in turn evaluates to (bool)true, thus returning the true branch of the// second ternary expression.?> 
0 0
原创粉丝点击