Jump to content

Removing specific items from a list


Junitar

Recommended Posts

Hi,

I would like to list all the items contained in a folder except for 2 or 3 specific ones.

For example, let's say I've item 1, item 2, …, item 10  in  /myFolder. I would like to list all the items of /myFolder but item 1, item 3 and item 4. I've come up with the following code which does the work but looks a bit awkward.

<?php
$dir = '/myFolder';
$filesDir = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileName = '';
foreach ($filesDir as $file) {
    $fileName = $file->getBasename();
    if ($fileName != 'item1' && $fileName != 'item3' && $fileName != 'item4') {
        echo $fileName.'<br>';
    }
}

Is there a simple and more elegant way to accomplish this?

 

Any help would be appreciated, thanks!

Link to comment
Share on other sites

Your current solution is far more efficient than constructing an array and using in_array() on each iteration, but there's an alternative to in_array() which is much less costly: Using the keys of an associative array.

<?php
$exclude = array(
  'item1' => 1,
  'item3' => 1,
  'item4' => 1
);
$dir = '/myFolder';
$filesDir = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileName = '';
foreach ($filesDir as $file) {
    $fileName = $file->getBasename();
    if(!isset($exclude[$fileName])) {
        echo $fileName.'<br>';
    }
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...