Reputation: 365
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
Upvotes: -1
Views: 993
Reputation: 3389
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">
Upvotes: 1
Reputation: 3215
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>
Upvotes: 1
Reputation: 1006
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>
Upvotes: 0
Reputation: 2957
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">';
}
?>
Upvotes: 1