Generating id in input via foreach

1

I'm having difficulty generating a number in each input id. I need to display 4 images, and I saved their names in the database separating them with a comma, then gave them an explode to display them in foreach.

$array = explode(',', $sqlImagem['enderecoImagem']);
foreach($array as $valores)
        {
            echo '<a href="#" id="'.$id.'"><img src="Admin/Pagina/Produtos/uploads/'.$valores.'"/></a>';

        }

But the problem is that I need to style a gallery with a thumbnail, and for that I need to generate a number (I tried to make an array but I did not succeed) input id as an example above.

Example of code when with just html, that would be how I need it ...

<a href="#" id="1"> <img src="Imagens/teste/k7 sunrace 1.jpg"/> </a>
<a href="#" id="2"> <img src="Imagens/teste/k7 sunrace.jpg"/> </a>
<a href="#" id="3"> <img src="Imagens/teste/k7.jpg"/> </a>
<a href="#" id="4"> <img src="Imagens/teste/k7 sunrace 2.jpg"/> </a>
    
asked by anonymous 30.11.2017 / 12:55

2 answers

3

You can use the position of the image itself in array :

foreach($array as $i => $valores) {
    echo "<a href='#' id='imagem_{$i}'><img src='Admin/Pagina/Produtos/uploads/{$valores}'/></a>";
}

So the output would look something like:

<a href="#" id="imagem_0"> <img src="Admin/Pagina/Produtos/uploads//k7 sunrace 1.jpg"/> </a>
<a href="#" id="imagem_1"> <img src="Admin/Pagina/Produtos/uploads/k7 sunrace.jpg"/> </a>
<a href="#" id="imagem_2"> <img src="Admin/Pagina/Produtos/uploads//k7.jpg"/> </a>
<a href="#" id="imagem_3"> <img src="Admin/Pagina/Produtos/uploads//k7 sunrace 2.jpg"/> </a>
    
30.11.2017 / 13:00
2

To start with number 1 as shown in question <a href="#" id="1"> do so:

$id=1;
foreach($array as $valores){
    echo '<a href="#" id="'.$id.'"><img src="Admin/Pagina/Produtos/uploads/'.$valores.'"/></a>';

    $id++;
}

example - Ideone

Or taking advantage of Anderson Carlos Woss's response

$i=1;
foreach($array as $valores) {
    echo "<a href=\"#\" id=\"imagem_{$i}\"><img src=\"Admin/Pagina/Produtos/uploads/{$valores}\"/></a>";
    $i++;
}

Sandbox example

    
30.11.2017 / 13:11