Reputation: 39
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,
Upvotes: 0
Views: 1637
Reputation: 46900
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);
}
Upvotes: 1