P.Davide P.Davide - 5 months ago 9
PHP Question

two for loop with two arrays and check if they match [half working]

I have this code, I use this code to print a map of teeth:

if($tip_dente == 2){
for($i=0; $i<=7; $i++){
for($j=0; $j<=$var_n; $j++){
if($array_p1n[$i]==$array_denti_new[$j]){
$pdf->Cell(0.5,1,$pdf->Image($array_p1[$i],$pdf->GetX(),$pdf->GetY(),0,1,'PNG'),1,C,1,false); // larghezza, altezza, txt, bordi, linea a capo, allineamento orizzontale, riempimento colore, ignorare
$pdf->Cell(0.2,1,'',0,0,C,false);
}else{
$pdf->Cell(0.5,1,$pdf->Image($array_p1[$i],$pdf->GetX(),$pdf->GetY(),0,1,'PNG'),0,C,1,false); // larghezza, altezza, txt, bordi, linea a capo, allineamento orizzontale, riempimento colore, ignorare
$pdf->Cell(0.2,1,'',0,0,C,false);
}
}
}
}


I use this code to browse the arrays and if they match the code prints an alternative image.
The code works indeed it prints an alternative image when the two arrays match but the problem is that it prints every tooth 4 times..
How can I fix this problem?

Using the function var_export I obtain this:

$array_p1n= array ( 0 => 18, 1 => 17, 2 => 16, 3 => 15, 4 => 14, 5 => 13, 6 => 12, 7 => 11, )
$array_denti_new= array ( 0 => '18', 1 => '17', 2 => '16', )


And it is ok because the first array is the one that I defined while the second array ($array_denti_new) is the array that I fill with elements took from the database. This is the array ($array_p1n) I created and it matches with the function var_export:
$array_p1n = array(18,17,16,15,14,13,12,11);


With my code I would like to print the $array_p1n and while doing this I would like to check if the elements inside the second array ($array_denti_new) match with the elements of first array. If so, print an alternative image

Answer

You can use in_array() function to check if an element exists in the array or not.

if($tip_dente == 2){
    for($i=0; $i<=7; $i++){
        if(in_array($array_p1n[$i], $array_denti_new)){
            $pdf->Cell(0.5,1,$pdf->Image($array_p1[$i],$pdf->GetX(),$pdf->GetY(),0,1,'PNG'),1,C,1,false); // larghezza, altezza, txt, bordi, linea a capo, allineamento orizzontale, riempimento colore, ignorare
            $pdf->Cell(0.2,1,'',0,0,C,false);
        }else{
            $pdf->Cell(0.5,1,$pdf->Image($array_p1[$i],$pdf->GetX(),$pdf->GetY(),0,1,'PNG'),0,C,1,false); // larghezza, altezza, txt, bordi, linea a capo, allineamento orizzontale, riempimento colore, ignorare
            $pdf->Cell(0.2,1,'',0,0,C,false);
        }
    }
}

Here's the reference:

Comments