2014-10-03 155 views
1

爲什麼不會從我回應的結果中刪除index.php?爲什麼不從其中刪除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的答案。

+0

你只是刪除從'$文件中的條目'陣列。這不會取消設置本地'$ file'字符串**,也不會跳過後面的'echo'。 – mario 2014-10-03 01:34:59

+0

顯然取消設置數組索引不會影響參考變量。您必須將某些內容分配給數組索引以更改引用。 – Barmar 2014-10-03 01:35:07

+0

在刪除元素後,你期待它回聲嗎? – Barmar 2014-10-03 01:37:05

回答

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 />