【问题标题】:Why isn't unset removing index.php from it's为什么不取消设置从中删除 index.php
【发布时间】:2014-11-28 02:31:39
【问题描述】:

为什么不取消设置从我回显的结果中删除 index.php?

$files = array(
    '0' => 'bob.php',
    '1' => 'index.php',
    '2' => 'fred.php'
);
foreach ($files as $key => &$file) {
    if(in_array($file, array('index.php'))) {
        echo 'test condition<br />'; // Yes, this condition is met
        unset($files[$key]);
    }
    echo '<a href="'.$file.'">'.$file.'</a><br />'."\n"; 
}

为了做到这一点,我实际上遵循了this stackoverflow question 的答案。

【问题讨论】:

  • 您只是从$files 数组中删除一个条目。这不会取消设置本地$file 字符串也不会跳过后续的echo
  • 显然取消设置数组索引不会影响引用变量。您必须为数组索引分配一些东西才能更改引用。
  • 删除元素后你希望它回显什么?

标签: php foreach unset


【解决方案1】:

由于$file 已经设置为index.php,它仍然会回显。关键实际上是未设置的,您可以通过在循环中使用 continue 来修复代码:

<?php

$files = array("home.php","index.php","example.php");
    foreach ($files as $key => &$file) {
        if(in_array($file, array('index.php'))) {
            unset($files[$key]);
            continue;
        }
        echo '<a href="'.$file.'">'.$file.'</a><br />'."\n"; 
    }
?>

结果:

<a href="home.php">home.php</a><br />
<a href="example.php">example.php</a><br />

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2014-09-20
    相关资源
    最近更新 更多