为什么不设置从中删除index.php

时间:2014-10-03 01:28:26

标签: php foreach unset

为什么不取消设置从我回响的结果中删除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的答案。

1 个答案:

答案 0 :(得分:0)

由于$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 />