Add variable whenever it is called

3

So I would like to know if there is any way in PHP to do the following, set an ex variable: $ contatorinicio="0"; and then whenever you call it in php it will add up another EX: $ counternew = $ counter + "'"; however each time I use an echo output the sum sum in EX sequence:

<?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 like this

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

With javascript until I got more would it be possible in pure php?

The @rray user gave me the hint and it worked as follows

<?php $contador = "0"; ?>
<?php echo ++$contador; ?> // imprime 1
<?php echo ++$contador; ?> // imprime 2
<?php echo ++$contador; ?> // imprime 3
    
asked by anonymous 09.01.2018 / 19:54

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;

According to 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;
    
09.01.2018 / 20:16
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 it becomes more scalable and better for maintenance

    
09.01.2018 / 20:54