Search code examples
phparraysloopsforeachstrpos

strripos array of needles inside a parent foreach loop


I'm inside a foreach loop from a scandir() wheres the directory files are $files as $file. I'm trying to simplify my strripos filetype exclusions by using an array of needles, rather than passing several strripos lines for each filetype.

This works:

if ($code !== 'yes'){
    $excluded = strripos($file, '.js')
                || strripos($file, '.pl')
                || strripos($file, '.py')
                || strripos($file, '.py')
                || strripos($file, '.rb')
                || strripos($file, '.css')
                || strripos($file, '.php')
                || etc.;
    } else {
        $excluded = '';
    } 

But this does not:

    if ($code !== 'yes'){
        $exclusions = array('.js, .pl, .py, .rb, .css, .php, etc.');
        foreach($exclusions as $exclude){
            $excluded = strripos($file, $exclude);   
        } 
    } else {
        $excluded = '';
    } 

$code is a shortcode attribute defined by the user as 'yes' or anything else = no.

Then when I get to the output, I check if $excluded has been defined as 'yes.' Like I said, it works with the first example, but I can't get an array to work. To reiterate, I'm already inside the $file loop from the scandir().

UPDATE

Tried using in_array but I'm probably doing something wrong. I've tried:

$exclusions = array('.js', '.pl', '.py', '.rb', '.css', '.php', '.htm', '.cgi', '.asp', '.cfm', '.cpp', '.dat', '.yml', '.shtm', '.java', '.class');
$excluded = strripos($file, (in_array($exclusions)));

And I've tried:

$excluded = strripos($file, (in_array('.js', '.pl', '.py', '.rb', '.css', '.php', '.htm', '.cgi', '.asp', '.cfm', '.cpp', '.dat', '.yml', '.shtm', '.java', '.class')));

No go.


Solution

  • Your array currently has only one element, which is a long string:

    '.js, .pl, .py, .rb, .css, .php, etc.'
    

    You should quote each of your string elements like this:

    $exclusions = array('.js', '.pl', '.py', '.rb', '.css', '.php', 'etc.');
    

    Try changing your code to this:

    $excluded = 'no';
    
    if ($code !== 'yes'){
        $exclusions = array('.js', '.pl', '.py', '.rb', '.css', '.php'); 
        foreach($exclusions as $exclude){
            $check = strripos($file, $exclude); 
            if ($check !== false) {
                $excluded = 'yes';
                break;
            }
        } 
    } 
    

    Start by assigning $excluded = 'no';. As soon as strripos returns anything other than false you assign $excluded = 'yes'; and break out of the foreach loop. This way you end up with either 'yes' or 'no'.