How can one efficiently loop through multiple PDF files and merge them dynamically in PHP?

To efficiently loop through multiple PDF files and merge them dynamically in PHP, you can use the TCPDF library which provides functionality to merge PDF files. You can iterate through each PDF file, add its content to the TCPDF object, and then output the merged PDF file.

require_once('tcpdf/tcpdf.php');

$pdf = new TCPDF();

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

$pdf->AddPage();

$pdf_files = ['file1.pdf', 'file2.pdf', 'file3.pdf'];

foreach ($pdf_files as $file) {
    $pdf_content = file_get_contents($file);
    $pdf->writeHTML($pdf_content, true, false, true, false, '');
}

$pdf->Output('merged_file.pdf', 'F');