gpt4 book ai didi

php - 带大括号的循环会导致错误的输出

转载 作者:可可西里 更新时间:2023-11-01 13:22:32 25 4
gpt4 key购买 nike

我创建了 2 个简单示例:

第一个例子:

<?php $arr = array(1,2,3,4,5); ?>

<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>

输出:

5 //Is this result wrong?

第二个例子:

<?php $arr = array(1,2,3,4,5); ?>

<?php foreach ($arr as $element) { ?>
<?php echo $element; ?>
<?php } ?>

输出:

12345

关于 PHP 语法,我错过了什么?

我知道有一个替代的 foreach 语法,但在我看来,两个显示的示例应该产生相同的输出。 (使用 PHP 版本测试的代码:5.6.12)

编辑:

我知道并不是每一行都需要标签。更准确地说:我想知道为什么这两个示例会给我 2 个不同的结果?

最佳答案

根据输出,我的猜测是:

<?php $arr = array(1,2,3,4,5); ?>

<?php foreach ($arr as $element) ?>
<?php { ?>
<?php echo $element; ?>
<?php } ?>

被解释为:

<?php
$arr = array(1,2,3,4,5);

foreach ($arr as $element);
{
echo $element;
}
?>

看起来像解释器中的错误? 查看 Rizier123 的评论:

  1. Not a bug: stackoverflow.com/q/29284075/3933332
  2. The brackets after the foreach()/Do nothing here/; is just a statement-group: php.net/manual/en/control-structures.intro.php

无论如何,按照您编写代码的方式,代码看起来很糟糕。请选择更简洁的代码。


看完问题下的评论我觉得Jon Stirling最好解释一下这个症状:

Just guessing, but perhaps the ?> in the first example is actually being taken as the statement end (loops can be used without braces). At that point, the loop has happened and $element is the last value. Then the braces are just take as a code block which you echo, which is 5.

关于php - 带大括号的循环会导致错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248878/

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