Generating id in input through foreach

Asked

Viewed 73 times

1

I’m having trouble generating a number in each input id. I need to display 4 images, and saved their name in the bank separating by comma, then exploded 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 thumbnail, and for that I need to generate a number (I tried to make an array, but I was not successful) input id as example above.

Example of code when with only html, that would be so I need...

<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>

2 answers

3


You can use the image’s own position on array:

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

So the exit would be 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>

2

To start with the number 1 as shown in the 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' answer

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

sandbox example

Browser other questions tagged

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