如何在循环两个数组时防止重复输出

I am trying to loop through two arrays at once. the first array contains the headings, the second array contains the data the user has imputed via the form. these values are then set to a pdf file. the problem I am having is that the output is being duplicated twice.

current output

first name user input
first name user input
last name user input
last name user input

output that I want

first name john
last name  smith

var dump

array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "Submit" } array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "Submit" } array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "Submit" } array(3) { ["fname"]=> string(5) "dkdkd" ["lname"]=> string(3) "kdk" ["submit"]=> string(6) "Submit" } 

code

<?php require('fpdf.php');?>
<?php

$headings = [
    "first_name" => "first Name",
    "last_name" => "last Name",
];

if(isset($_POST['submit'])) {
    $pdf = new FPDF();
    $pdf->AddPage();

    foreach ($headings as &$value) {
        foreach ($_POST as $key => $data) {
            if($key == 'submit') {
                continue;
            }    

            $pdf->SetFont('Arial','B',16);
            $pdf->write(40,"$value");
            $pdf->write(40,"$data");
            $pdf->ln(10);
        }
    }
    $pdf->Output();
}
?>

Firstly, this is unexpected behavior because the second loop should be repeated as first name, last name, first name, last name. (see what I mean here).

$heading = ['first name', 'last name'];

The above snippet of your code shows that you have 2 entries in your array. Therefore, your inner foreach() loop will be repeated twice since it is wrapped inside it. A better understanding:

foreach(... as ...) // 2 entries
   foreach(... as ...) // 3 entries that will be repeated twice ^

You can achieve this using Array index's with a counter.

$i = 0; // index start at 0

foreach($_POST as $k => $v) {
    if($k == "submit") continue;

    $pdf->write(40, $heading[$i++]);
    $pdf->write(40, $v);
    [...]
}

Hope this helped your duplication issue.
tldr: See it working here.

You can do something like this:

$duplicate = array();
foreach ($... as $...):
    if (in_array($...., $duplicate))
    continue; //if we already have that id, skip it
    $duplicate[] = $...;
endforeach

Hope this helps.