-1

I try to print images with a for loop but the images dont load.

<?php
$imagenes = array('1.png', '2.jpg', '3.png', '4.jpg','IMG_0105.JPG');
 ?>
  <div class="container">
    <div class="row">
      <div class="col-md">
        <?php
              for ($i=0; $i < 4; $i++) {
              echo '<img src = \"$imagenes[$i]\"  width = \'100px\' height = \'100px\';>';
              }
         ?>
      </div>
    </div>
  </div>

The images are in the same folder as the .php file

1
  • echo "<img src='$imagenes[$i]' width='100px' height='100px'>"; Commented Mar 24, 2019 at 23:05

4 Answers 4

1

Edit: Added additional solutions based on answer from @nik

This will never work because variables are not evaluated inside of single quoted strings.

Make sure that your use a string inside double quotes. Or use string concatenation to build the HTML tag. Also, you image tag has a semicolon inside of it that might break the tag.

So you can do this ...

echo "<img src=\"{$imagenes[$i]}\" width=\"100px\" height=\"100px\">";

or

echo "<img src=\"" . $imagenes[$i] . "\" width=\"100px\" height=\"100px\">";

or

<img src="<?= $imagenes[$i]; ?>" width="100px" height="100px">

or

<img src="<?php echo $imagenes[$i]; ?>" width="100px" height="100px">
Sign up to request clarification or add additional context in comments.

Comments

1

Use foreach for this. And for concatinate string with var - use . (dot)

       <?php
             foreach ($imagenes as $image) {
                echo '<img src = "'.$image.'"  width = "100px" height = "100px">';
             }
        ?>

Comments

1

This would make it simplier:

<div class="container">
  <div class="row">
    <div class="col-md">
      <?php foreach ($imagenes as $url) { ?>
        <img src="<?php echo $url ?>" width="100px" height="100px">
      <?php } ?>
    </div>
  </div>
</div>

Comments

0

I think its the way you're escaping the characters, you can just use concatenation on $images:

<div class="container">
    <div class="row">
        <div class="col-md">
            <?php
            for ($i=0; $i < 4; $i++) {
                echo '<img src = '.$imagenes[$i].' width="100px" height ="100px";>';
            }
            ?>
        </div>
    </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.