Search code examples
phpforeachfpdf

fpdf generate multiple pages using a foreach loop


I'm new to fpdf and I have this short code that prints the values of an array. My problem is that I can't figure out how to output these value on separate pages.

My code:

<?php
require('fpdf.php');
$pdf = new FPDF();

//Create an array
$myarray = array(1,2,3);

//loop through the array with a foreach and print the results on different pages
foreach($myarray as $value)
{
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);  
$pdf->Cell(40,10,$value);
$pdf->Output();

}

?>

Currently the code only prints the first value and stops. Your assistance is highly valued.

Thank you.


Solution

  • You must invoke the output function outside of your foreach. In your function it's invoked at the first cycle and interrupt the cycle to the first time.

    require('fpdf.php');
    $pdf = new FPDF();
    
    $myarray = array(1,2,3);
    
    $pdf->SetFont('Arial','B',16);  
    foreach($myarray as $value){
        $pdf->AddPage();
        $pdf->Cell(40,10,$value);
    }
    $pdf->Output();