为什么不是';t取消设置从中删除index.php';s

为什么不是';t取消设置从中删除index.php';s,php,foreach,unset,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<

为什么不取消设置,将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"; 
}
$files=数组(
“0”=>“bob.php”,
'1'=>'index.php',
“2”=>“fred.php”
);
foreach($key=>&$file形式的文件){
if(在数组($file,array('index.php'))中){
echo“测试条件
”;//是,满足此条件 取消设置($files[$key]); } 回显“
”。“\n”; }

为了做到这一点,我实际上遵循了。

的答案,因为
$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 />



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