Jump to content

Eliminating array elements not containing string


anderson_catchme

Recommended Posts

So I'm trying to unset array elements that don't contain "thumbnail" in the filename. Seems simple, but it's not working.

 

function generateImage3 ($category, $imageornot, $Imagepointer) {
    if($imageornot == 1){
    $var = get_cwd_uploads().'\\'.$Imagepointer; // get_cwd_uploads() is a custom function
    $scanned_directory = array_diff(scandir($var), array('..', '.'));
    foreach($scanned_directory as $elements){
    $pos = strpos($elements, 'thumbnail');
    if($pos === FALSE){
            unset($scanned_directory[key($elements)]);
        }
    }

// irrelevant code

 

Any help appreciated.

We don't really like deleting stuff. What we would like is if you shared what you had to do to fix your problem.

 

And while I'm here, next time please actually describe the problem ("it's not working" doesn't mean much) and use

 tags around your code.

You want to use the key from the foreach.  Also you want to use !== false because it exists:

foreach($scanned_directory as $key => $elements){
    $pos = strpos($elements, 'thumbnail');
    if($pos !== FALSE){
        unset($scanned_directory[$key]);
    }
}

However this is much simpler (replaces all of your code):

$files = preg_grep("/thumbnail/", glob("$var/*.*"), PREG_GREP_INVERT);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.