1

Why won't unset remove index.php from the results I am echoing out?

$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"; 
}

To make this I actually followed the answers for this stackoverflow question.

Community
  • 1
  • 1
trimidium1
  • 19
  • 4
  • You're just removing an entry from the `$files` array. That doesn't unset the local `$file` string **nor skip** the subsequent `echo`. – mario Oct 03 '14 at 01:34
  • Apparently unsetting the array index doesn't affect the reference variable. You have to assign something to the array index to change the reference. – Barmar Oct 03 '14 at 01:35
  • What are you expecting it to echo after you remove the element? – Barmar Oct 03 '14 at 01:37

1 Answers1

0

Since $file is already set to index.php it still echos. The key is in-fact unset though, and you can fix the code by using a continue in the loop:

<?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"; 
    }
?>

Result:

<a href="home.php">home.php</a><br />
<a href="example.php">example.php</a><br />
l'L'l
  • 44,951
  • 10
  • 95
  • 146