Home >Backend Development >PHP Tutorial >php-little pitfalls of weak typing

php-little pitfalls of weak typing

WBOY
WBOYOriginal
2016-08-08 09:31:381179browse

An issue discussed in the group today, record it.

The origin of the problem is
var_dump(md5('240610708') == md5('QNKCDZO')); //true
Two md5 strings, compared with the comparison operator (==), they are actually equal of.
Output the following two values:
md5('240610708') //0e462097431906509019562988736854
md5('QNKCDZO') //0e8304004519934940580242199033 91

When I saw the result, I felt that it was intval at first glance, so 0 == 0 returned true.
After being reminded later, I found out that this was not the case.
php comparison operator:
http://php.net/manual/zh/language.operators.comparison.php
Example:

如果比较一个数字和字符串或者比较涉及到数字内容的字符串,则字符串会被转换为数值并且比较按照数值来进行。此规则也适用于 switch 语句。当用 === 或 !== 进行比较时则不进行类型转换,因为此时类型和数值都要比对。
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
?>

In other words, this equality is not because the two strings are intval, and become 0=0
but is numericized 0e4xxx == 0e8xxx, which is scientific notation, 0*10 to the nth power, that is, 0.0000 and 0.00000000
, so there will be equal results.

The above has introduced the small pitfalls of php-weak typing, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP carousel lottery demoNext article:PHP carousel lottery demo