PHP 从文件中读取并添加一个

发布于 2024-12-16 18:45:30 字数 347 浏览 2 评论 0原文

假设我有文件 foo.txt,其中有一位数字 0。 然后我读取该文件并将 0 存储到数组中。我想将数字加 1,所以我只使用简写运算符 ++ 但它不起作用,但 += 却可以。

$poo = file("foo.txt");
$poo[0]++;
echo $poo; // gives me 0
$poo[0] += 1;
echo $poo; // gives me 1

我知道当我读取 poo[0] 的文件值时,它是带有空格的字符串 "0 " 但为什么它不适用于 ++ >?

Let's say I have file foo.txt in which I have one digit which is 0.
Then I read that file and 0 is stored into array. I want to increment number by 1 so I just use shorthand operator ++ but it doesn't work however += does.

$poo = file("foo.txt");
$poo[0]++;
echo $poo; // gives me 0
$poo[0] += 1;
echo $poo; // gives me 1

I know that when I read file value of poo[0] is string with space "0 " but why it doesn't work with ++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

马蹄踏│碎落叶 2024-12-23 18:45:30

您在使用隐式类型转换的语言中遇到了一个常见错误。当您将 foo.txt 的内容读入 $poo 时,该值将存储为字符串。

当您告诉 PHP 使用 ++ 递增字符串时,PHP 必须尝试确定您的意思。 $poo 包含一个字符串(不是数字),因此 PHP 不知道您要添加 0 + 1 的值;相反,它认为您正在尝试执行字符串操作并提供意外结果。

在第二种情况下,隐式类型表明,由于您在等式右侧使用整数(而不是字符串),因此您也必须将左侧转换为整数。

为了安全起见,您应该明确告诉 PHP 解释器您正在尝试对两个数字执行数学运算:

$poo[0] = (int)$poo[0] + 1;

有关详细信息,请参阅 PHP:类型杂耍

You have encountered a common error in languages that use implicit type casting. When you read the contents of foo.txt into $poo, the value is stored as a string.

When you tell PHP to increment the string using ++, PHP has to try to determine what you mean. $poo contains a string (not a number) so PHP doesn't know that you want to add the value of 0 + 1; instead, it thinks you are trying to perform a string operation and provides an unexpected result.

In the second case, the implicit typing figures out that, since you use an integer (not a string) on the right side of the equation, you must want to cast the left side to an integer as well.

To be safe, you should explicitly tell the PHP interpreter that you are trying to perform a mathematical operation on two numbers:

$poo[0] = (int)$poo[0] + 1;

For more information please see PHP: Type Juggling.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文