Add variable whenever called

Asked

Viewed 430 times

2

well then I would like to know if there is some form in PHP to do the following, define a variable ex: $contactorinicio = "0"; and then whenever you call her in php she goes adding another EX: $counter = $counter + "'"; however each time I use an echo exit the result summed in sequence EX:

<?php $contador = "0";
   $contadornovo = $contador++;

<a href="#menu<? echo $contadornovo"; ?>" >produtos</a>
<a href="#menu<? echo $contadornovo"; ?>" >fotos</a>

in case it would be printed so

<a href="#menu1" >produtos</a>
<a href="#menu2" >foto</a>

con javascript ate consegui mais seria possivel isso no php puro?

The @rray user gave me the hint and it worked like this

<?php $contador = "0"; ?>
<?php echo ++$contador; ?> // imprime 1
<?php echo ++$contador; ?> // imprime 2
<?php echo ++$contador; ?> // imprime 3
  • Anderson did not understand, from what I read apparently you showed what you wanted to do.

  • Calling it in PHP in what way?

  • Can do ++$contadornovo;

  • like the model below, every time I call her $countered it keep adding +1 EX: 1st time $countered = 1 $countered = 2 $countered = 3 understood?

  • @rray the result was the same stayed 1 1

  • @Juliohenrique97 updated the post with example

  • Tried to thus ?

  • 1

    did it work out if it had gotten the wrong name <? php $counter = "0"; ? > <? php echo ++$counter; ? > <? php echo ++$counter; ? > <? php echo ++$counter; ?>

Show 3 more comments

2 answers

5


Just one variable - ideone

$contador = 0;

echo '<a href="#menu'.++$contador .'">produtos</a>'. PHP_EOL;
echo '<a href="#menu'.++$contador .'">fotos</a>'. PHP_EOL;

As per comment <id="1"> <a href="1"> ideone

$contador = 0;

echo '<div id="'.++$contador .'"><a href="#menu'.$contador .'">produtos</a></div>'. PHP_EOL;
echo '<div id="'.++$contador .'"><a href="#menu'.$contador .'">fotos</a></div>'. PHP_EOL;
  • yes yes it was that same , but Aki another doubt has to display the same result 2x before jumping next pro pq my code this so <id="1"> <a href="1"> your call <id="++$counter"> <a href="++$counter"> will get <id="1"> <a href="2"> this is possible, make the counter give the result 2x?

  • what I would like to know is if it was possible only using a variable and yes I changed its code it worked out https://ideone.com/ljhpWu << just call the variable without the + it will give the previous result already added, anyway it worked out well

1

suggestion:

$opcoes = ["proutos", "fotos"];
foreach($opcoes as $id => $opcao){
    echo '<a id="'.++$id.'" href="#menu'.$id.'">'.$opcao.'</a>';
}

you have the same result however gets more scalable and better for maintenance

Browser other questions tagged

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