Loop(repeat) HTML/PHP

Asked

Viewed 57 times

0

Good afternoon, I have a repetition problem in my code. I was wondering if there is any way to decrease the code that is very extensive due to this. Follows code:

<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=<?php echo $nova[0]?>&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);"><?php echo ($newuasg[0] . "/" . $newuasg[1])?></a> 
<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=<?php echo $nova[1]?>&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);"><?php echo ($newuasg[2] . "/" . $newuasg[3])?></a> 
<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=<?php echo $nova[2]?>&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);"><?php echo ($newuasg[4] . "/" . $newuasg[5])?></a> 
<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=<?php echo $nova[3]?>&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);"><?php echo ($newuasg[6] . "/" . $newuasg[7])?></a> 
<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=<?php echo $nova[4]?>&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);"><?php echo ($newuasg[8] . "/" . $newuasg[9])?></a>

This is just one part of the code that repeats in this same pattern for another 2000 lines. My problem is in the variable, $nova and $newuasg. Thanks in advance.

I used @Vitor Carnaval’s reply and it worked perfectly.

2 answers

1


If your intention is to maintain the architecture of these arrays and print them you can use the following solution that has very explicit variables:

$par = 0;
$impar = 1;

for ($i = 0; $i < count($nova); $i++) {
    echo '<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=' . $nova[$i] . '&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);">' . $newuasg[$par] . '/' . $newuasg[$impar] . '</a><br>'; 
    $par = $par + 2;
    $impar = $impar + 2;
}

0

Use the printf in a loop for:

<?php
for ($i=0;$i<count($nova);$i++) {
  printf('<a href="https://www.comprasnet.gov.br/pregao/fornec/Acompanhar1.asp?prgCod=%s&pagina=1&botao=T" target="inframe" onclick="mostrarAtivo(this);">%s/%s</a>',
    $nova[$i], $newuasg[$i*2], $newuasg[$i*2+1]);
  echo PHP_EOL;
}
?>

Basically the printf replaces the %s (see type specifiers) in the first argument for the following arguments, in order.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.