Search code examples
phparraysif-statementforeachstrpos

Finding a string by looping through an array php


I have this array $filelist

Array ( [0] => . [1] => .. [2] => .DS_Store [3] => 11-96.eml [4] => 11-97.eml ) 

Which is a list of all files in a particular directory... Sometimes there is no .DS_Store file, sometimes there is, sometimes there are 2 eml files, sometimes there are as many as 6. I'm trying to loop through and find the first array position a .eml file exists so that I can work out how many file are eml and where to start referencing the array.. I have tried...

 function firstFileInList($filelist) {
        $x = 0;
        foreach ($filelist as $value) {
          if(strpos($filelist, ".eml") == false) {
              $x = $x + 1;   
             //break;
            }

          }

          return $x;
      }

This returns 5, if I include the break it returns 1 and I was expecting to get 4.

Please could somebody point me in the right direction or even if there is a completely better way to do this then I would be more than grateful to see that...

Thanks Paul,


Solution

  • break exists every PHP loop directly when it is called, even if there are other elements. Use continue to get to the next element.

    Based on your question

    I'm trying to loop through and find the first array position a .eml file exists

    function firstFileInList($filelist) {
        foreach($filelist as $k => $v)
          if(strpos($v, ".eml") !== false)
            return $k;
    
        return false;
    }