Reputation: 3
I'm trying to make my life a little easier and use a PHP foreach loop to write out loads of near-identical code, however I'm having trouble getting it to recognise $a, $b and $a$b inside of the echo ''.
If I replace $a$b with, for example, '1.jpg', it iterates the same image for each line in the array, but I'd much rather use the array to enter the file names.
Does anyone have any ideas?
Thanks in advance.
<?php
$array = [
['1', '.jpg'],
['2', '.jpg'],
];
foreach ($array as list($a, $b)) {
echo '<div class="col-md-6 col-lg-4 mb-5">
<div class="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal$a">
<div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div>
</div>
<img class="img-fluid" src="assets/img/portfolio/$a$b" alt="" />
</div>';
}
?>
Upvotes: 0
Views: 156
Reputation: 1418
When iterating, you pass the contaent of each element in the loop. In you case the first content will be ['1', '.jpg'] (an array) and the second ['2', '.jpg'].
So to access it, just use $item[0] and $item[1].
Now to concatenate it in echo, just use the normal 'some text' . $my_data . 'some other text'.
Indeed, $my_data would work only if your string use double quote
See documentation here: https://www.php.net/manual/en/language.operators.string.php
$array = [
['1', '.jpg'],
['2', '.jpg'],
];
foreach ($array as list($a, $b)) {
echo '<div class="col-md-6 col-lg-4 mb-5">
<div class="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal$a">
<div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div>
</div>
<img class="img-fluid" src="assets/img/portfolio/'. $a . $b .'" alt="" />
</div>';
}
Upvotes: 2