php - foreach function not working correctly

829

The foreach function is not working as I expect:

<?php

$folders = scandir('../Users/');  
foreach($folders as $item):
    if ((substr($item, 0, 1) == '.') || (preg_match("/\.php$/", $item)))
          continue;

     if (is_dir("../Users/$item"))
          $target_folders = @scandir("../Users/$item/processed/");
     foreach($target_folders as $target_item){

         if ((!preg_match("/^[.]/",$target_item))
           || (!is_dir("../Users/$item/processed/$target_item"))){
          if ((substr($target_item, 0, 1) == '.'))
             continue;      
          }
      }
      $srcfile= ("../Users/$item/processed/".$target_item);
      $dstfile= ("processed/".$target_item);
      copy($srcfile, $dstfile);
      unlink($srcfile);
endforeach;
array_map('unlink', glob("processed/*.zip"));
?>

honestly i dont know what is going wrong with it since its duplicate is running just fine. Right now it is only moving one of the files instead of moving all of them. As I said its duplicate works just fine if you would like me to post that as well let me know.

246

Answer

Solution:

moving logic is outside the loop, I suppose here is the proper version:

$folders = scandir('../Users/');
foreach($folders as $item)
{
    if ((substr($item, 0, 1) == '.') || (preg_match("/\.php$/", $item)))
        continue;
    if (is_dir("../Users/$item"))
    {
        $target_folders = @scandir("../Users/$item/processed/");
        foreach($target_folders as $target_item)
        {
            if ((!preg_match("/^[.]/",$target_item)) || (!is_dir("../Users/$item/processed/$target_item")))
            {
                if ((substr($target_item, 0, 1) == '.'))
                    continue;
                $srcfile= ("../Users/$item/processed/".$target_item);
                $dstfile= ("processed/".$target_item);
                copy($srcfile, $dstfile);
                unlink($srcfile);
            }
        }
    }
}
array_map('unlink', glob("processed/*.zip"));

People are also looking for solutions to the problem: Creating a different array related to different times a loop happens php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.