Jump to content
Sign in to follow this  
Junitar

Removing specific items from a list

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!

Share this post


Link to post
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>';
    }
}

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...