【问题标题】:PHP foreach variable scope issuePHP foreach变量范围问题
【发布时间】:2020-06-12 18:38:29
【问题描述】:

我有一个充满关联数组的数组,如下所示:

$arr = [
  ['title' => 'My title', 'content' => 'lorem ...', comments: 'lorem ipsum'],
  ['title' => 'My title 2', 'content' => 'lorem ...'],
  ['title' => 'My title 3', 'content' => 'lorem ...'],
  ['title' => 'My title 4', 'content' => 'lorem ...', comments: 'lorem ipsum'],
];

如您所见,其中一些没有comments。

问题是,我有一个这样的 foreach 循环:

<?php foreach($arr as $key => $value){
  extract($value);
?>
  <div>
    ...etc
    <?php if($comment): ?>
       <span><?= $comment ?></span>
    <?php endif; ?>
  </div>
<?php } ?>

在第二次迭代中,变量$comments 现在保存数组中第一项的值,因为它没有在关联数组中找到属性并使用最后一个,从而破坏了if 语句.

有什么方法可以避免这种情况,而不必在原始数组中添加 comments: null 或其他内容?

【问题讨论】:

  • 不使用提取。正确命名变量。您的 IDE 也会对此感到高兴。
  • if (isset($value['comment'])) { ... }
  • 在 PHP 中变量的作用域是函数,而不是迭代块。因此,当循环重复时,循环中设置的变量不会消失。
  • 不要使用extract()。你不需要它。永远。
  • @axiac 没有必要。 extract(),当 ̶c̶o̶r̶r̶e̶c̶t̶l̶y̶ 使用时,会很快导致无法维护的代码,因此,授予终身工作

标签: php


【解决方案1】:

只需使用isset 来检查变量$elem['comments'] 是否存在:

<div>
<?php
foreach($arr as $key => $elem){
    if(isset($elem['comments'])){
        // Comments exists here
        echo "<span>".$elem['comments']."</span>";
    }else{
        // Comments do not exists here, so don't echo anything
    }
}
?>
</div>

或者使用array_key_exists检查comments键是否在数组elem中:

<?php
foreach($arr as $key => $elem){
    if(array_key_exists('comments', $elem)) {
        // Comments exists here
        echo "<span>".$elem['comments']."</span>";
    }else{
        // Comments do not exists here, so don't echo anything
    }
}
?>

请注意:

isset() 不会为对应于 NULL 的数组键返回 TRUE 值,而 array_key_exists() 有。

因此,在您的用例中,我建议您使用 isset,因为您丢弃带有 null 值的现有 comments 键,就像 comments 键不存在一样。

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 2011-04-10
    • 2011-08-11
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    相关资源
    最近更新 更多