Search code examples
phparraysglob

Exclude file name when using glob and array_slice


This has to be simple: I'm using glob to build a list of links to all files in a directory (i.e., index.php, somefile.php, someotherfile.php), but I need to exclude the file name/path index.php before the array_slice.

For some reason, in these two examples, I can exclude index.php after the array_alice, but not before. What am I doing wrong?

This doesn't remove the filename/path index.php:

chdir('/dir/tree/');

foreach (glob("*.php") as $path) {

$files[$path] = filemtime($path);

} arsort($files);

if($path != 'index.php') {

foreach (array_slice($files, 0, 3) as $path => $timestamp) {

print '<a href="'. $path .'">'. $path .'</a><br />';
}
}

This removes index.php, but it is after the array_alice, so I get two links printed instead of three:

chdir('/dir/tree/');

foreach (glob("*.php") as $path) {

$files[$path] = filemtime($path);

} arsort($files);

foreach (array_slice($files, 0, 3) as $path => $timestamp) {

if($path != 'index.php') {

print '<a href="'. $path .'">'. $path .'</a><br />';
}
}

Solution

  • You are putting your check after loop.

    <php
    foreach (glob("*.php") as $path) {
    //---------------------------^
        $files[$path] = filemtime($path);
    }
    arsort($files);
    
    if($path != 'index.php') {}
    //---^
    

    Put it in your loop like this:

    foreach (glob("*.php") as $path) {
        if($path == 'index.php') {
            continue;
        }
        $files[$path] = filemtime($path);
    }