是否有更好的方法来检查PHP中的误报类型杂耍?

时间:2016-12-31 10:32:47

标签: php variables

有没有更好的方法来检查php中弱变量类型的误报检查(比较两个值)?

0 ==:true,确切为假

4 == 1:true,确切为假

0 ==:true,确切为假

0 == 0:是,确切为假

0 ==:true,确切为假

0 == a:true,确切为假

1 == 01:true,确切为假

==:true,确切为假

3 == 3只狗:是的,确切的错误

100 == 1e2:true,确切为假

100 == 100:true,确切为假

abc == 1:true,确切为假

123 == 123:true,确切为假

123 == +0123:true,确切为假

<?php
        function is_equal($value1, $value2, $exact=0) {
            $output = "{$value1} == {$value2}: ";
            switch($exact) {
                case 0:
                    if ($value1 == $value2) {
                        $output .= "true, ";
                    } else {
                        $output .= "false, ";
                    } //break;
                case 1:
                    if ($value1 === $value2) {
                        $output .= "\texact true<br>";
                    } else {
                        $output .= "\texact false<br>";
                    } break;
            }
            return $output;
        } //endof is_equal
        echo is_equal(0,false);
        echo is_equal(4,true);
        echo is_equal(0,null);
        echo is_equal(0,"0");
        echo is_equal(0,"");
        echo is_equal(0,"a");
        echo is_equal("1","01");
        echo is_equal("",null);
        echo is_equal(3,"3 dogs");
        echo is_equal(100,"1e2");
        echo is_equal(100,100.00);
        echo is_equal("abc",true);
        echo is_equal(123,"    123");
        echo is_equal(123,"+0123");

    ?>

1 个答案:

答案 0 :(得分:1)

PHP在比较之前将值转换为兼容类型。

要比较类型和值,请使用三等于。

1 == "1" // true
1 === "1" // false

Comparison operators文档页面