I'm just trying to loop through the array and echo it 3 times inside the div but here I got confused and why is it throwing me an undefined array key. If I put fixed numeric value inside $arr[i] then its running properly but why isn't it picking up the value of i? What am I missing?
Please help me to solve the problem and Thanks in advance.
Here's the code below.
<?php
$arr = array("Gallery-1.jpg","Gal-2.jpg","Gal-3.jpg","gal-4.jpg","gal-5.jpg");
$i = 0;
for ($i=0; $i<3; $i++) {
echo "<div class='col-lg-4 col-md-6 portfolio-item filter-programs'>
<img src='assets/img/portfolio/.$arr[i].' class='img-fluid' alt=''>
<div class='portfolio-info'>
<h4>Programs 1</h4>
<p>Programs</p>
<a href='assets/img/portfolio/.$arr[i].' data-gallery='portfolioGallery'
class='portfolio-lightbox preview-link' title='App 1'><i class='bx bx-plus'></i></a>
</div>
</div>";
}
?>
My Answer:
It looks like you are trying to access the array key using the variable `$i` inside the loop. However, in PHP, you need to use square brackets `[]` to access array elements, not parentheses `()`.
Here is the corrected code:
php
$arr = array("apple", "banana", "cherry");
for ($i = 0; $i < count($arr); $i++) {
echo "" . $arr[$i] . "";
}
This code will loop through the array and echo each element inside a `
` tag. Make sure to use square brackets `[]` to access array elements.
Rate this post
3 of 5 based on 8818 votesComments