Jump to content

help with array foreach


newbtophp

Recommended Posts

I have 2 arrays with the the same amount of elements, i want to loop through them both and then link the titles with the $pages (href location). Currently its not echoing what I expect it too (presumably due to me looping it incorrectly?)

 

Currently its outputting :(:

 

<a href="life-death-peter-sellers">Peter Pan</a><br>
<a href="life-death-peter-sellers">Peter and Vandy</a><br>
<a href="life-death-peter-sellers">The Life and Death of Peter Sellers</a><br>
<a href="peter-and-vandy">Peter Pan</a><br>
<a href="peter-and-vandy">Peter and Vandy</a><br>
<a href="peter-and-vandy">The Life and Death of Peter Sellers</a><br>
<a href="peter-pan">Peter Pan</a><br>
<a href="peter-pan">Peter and Vandy</a><br><a href="peter-pan">The Life and Death of Peter Sellers</a><br>

$pages contains:

 

Array ( [0] => life-death-peter-sellers [1] => peter-and-vandy [2] => peter-pan ) 

 

$titles contains:

 

Array ( [0] => Peter Pan [1] => Peter and Vandy [2] => The Life and Death of Peter Sellers ) 

 

My current code:

 

foreach($pages as $page){
foreach($titles as $title){
echo "<a href=\"".$page."\">".$title."</a><br>";
}
}

 

Expected Output:

 

<a href="life-death-peter-sellers">Peter Pan</a><br>
<a href="peter-and-vandy">Peter and Vandy</a><br>
<a href="peter-pan">The Life and Death of Peter Sellers</a><br>

 

All help is appreciated  :-\ :-\

Link to comment
https://forums.phpfreaks.com/topic/193137-help-with-array-foreach/
Share on other sites

because you have nested for loops you $page array is looping through every $title value, hence getting 3x the output.

 

if you only have a 1-1 relationship (one page per title and vice versa) on your values just do:

for($i =0; $i < count($page); $i++){

echo "<a href=\"".$page[$i]."\">".$title[$i]."</a><br>";

}

 

other option would be to combine those two arrays.

 

Thanks figured that aspect out, but got another issue,

 

Say if I have an array like:

 

Array ( [0] => peter-pan [2] => life-death-peter-sellers [4] => peter-and-vandy )

 

How can I turn it into:

 

Array ( [0] => peter-pan [1] => life-death-peter-sellers [2] => peter-and-vandy )

 

I've tried sort but that rearrange the grouping, I want the elements to stay in the same place, but ensure that their in numerical order.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.