Reputation: 15
I'm fairly new to PHP and still struggling with the simplest of tasks. I have searched the internet but could not find or figure out the right solution.
Let's say that I've got two pages: one is index.php, where I want to display a list of hyperlinks and names of respective pages those links lead to. The other is functions.php, where I've stored an array containing my links and titles. Also, I'm aware that arrays could be stored in a better place than functions.php, but that's beside the point, for now.
This is my HTML on the index.php page:
<ul class="row">
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
</ul>
This is my array:
$pageitems = array (
array('link' => 'https://website-one.com', 'title' => 'Website 1'),
array('link' => 'https://website-two.com', 'title' => 'Website 2'),
array('link' => 'https://website-three.com', 'title' => 'Website 3'),
);
And this is my function that I hoped would loop through each sub-array and display the link and title in the page items on the index.php page:
$i = 0;
foreach ( $pageitems as $pageitem ) {
$i++;
foreach ( $pageitem as $key => $value )
{
return $pageitem['link'];
return $pageitem['title'];
}
}
But no - it only repeats the first link and title pair (website-one.com, Website 1) on every page item on the index page, like the loop gets stuck after the first iteration.
Upvotes: 0
Views: 72
Reputation: 15131
I guess you have to iterate the array you have and put the li
inside a foreach loop, like this:
<ul class="row">
<?php
$pageitems = array (
array('link' => 'https://website-one.com', 'title' => 'Website 1'),
array('link' => 'https://website-two.com', 'title' => 'Website 2'),
array('link' => 'https://website-three.com', 'title' => 'Website 3'),
);
foreach ($pageitems as $pageitem) {
?>
<li class="col-6 col-lg-4">
<a class="hyperlink" href="<?php echo $pageitem['link'] ?>">
<div class="page-item">
<**SVG icon goes here, disregard**>
<span><?php echo $pageitem['title'] ?></span>
</div>
</a>
</li>
<?php
}
?>
</ul>
If it's better for you to have the $pageitems
in a different file, you can use include('function.php');
any point before the foreach loop.
Upvotes: 1