gpt4 book ai didi

php - 为什么 PHP 将 String 转换为 Integer?

转载 作者:可可西里 更新时间:2023-11-01 00:16:57 24 4
gpt4 key购买 nike

我想知道 PHP 在什么条件下决定何时将 String 转换为 Integer 以及其他方式

例子:

$key = 0;
$test = 'teststring';
if($key == $test) {
echo "Why, tell me why!";
}
else {
echo "That's the way love goes...";
}

我知道我应该使用“===”来获得更好的结果,但我很想知道为什么 PHP 决定将字符串转换为整数而不是相反。

最佳答案

来自 PHP 手册:

a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

参见 Type JugglingType Comparison TableString conversion to numbers详情:

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

还有 chapter on Strings:

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

还有(虽然已经由 deceze 给出)chapter on Comparison Operators :

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

关于php - 为什么 PHP 将 String 转换为 Integer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5741476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com