0

Please help me somebody as to how to read multiple files from a directory and merge them into a single array in PHP. I have developed a code but it does not work, as follows:

<?php
$directory = "archive/";
$dir = opendir($directory);
$file_array = array(); 
while (($file = readdir($dir)) !== false) {
  $filename = $directory . $file;
  $type = filetype($filename);
  if ($type == 'file') {
     $contents = file_get_contents($filename);
     $texts = preg_replace('/\s+/', ' ',  $contents);
      $texts = preg_replace('/[^A-Za-z0-9\-\n ]/', '', $texts);
      $text = explode(" ", $texts);
  }
 $file_array = array_merge($file_array,  $text);
}
$total_count = count($file_array);
echo "Total Words: " . $total_count;
closedir($dir);  
?>

But the output of this code indicates "Total Words: 0", notwithstanding, I have two files in the directory which account for 910 words collectively.

Regards,

1
  • What does echo count($text) show? Commented Jun 19, 2014 at 5:53

1 Answer 1

1

Small mistake:

$file_array=array_merge($file_array,  $text);

Should be inside the if block, not outside it. Rest of your code is fine. Like this

if ($type == 'file') {
     $contents = file_get_contents($filename);
     $texts = preg_replace('/\s+/', ' ',  $contents);
     $texts = preg_replace('/[^A-Za-z0-9\-\n ]/', '', $texts);
     $text = explode(" ", $texts);
     $file_array = array_merge($file_array,  $text);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Hanky for your handy reply. It solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.