newbtophp Posted July 28, 2010 Share Posted July 28, 2010 Hi, I have an array: Array ( [0] => index.php [1] => Home [2] => page.php?id=23 [3] => Page ) How would I loop through it so I can link the previous value to the next value within the array e.g.: <a href="index.php">Home</a> <a href="page.php?id=23">Page</a> Link to comment https://forums.phpfreaks.com/topic/209160-how-to-foreach-this-array/ Share on other sites More sharing options...
ChemicalBliss Posted July 28, 2010 Share Posted July 28, 2010 Are you creating this array? I would personally use a multi-dimensional associative array such as; Array ( [0] => Array ( [link] => index.php [name] => Home ) [1] => Array ( [link] => page.php?id=23 [name] => Page ) ) Then use this to loop; <?php foreach($array As $item){ echo('<a href="'.$item['link'].'">'.$item['name'].'</a>'); } ?> ---- For your case you need to use a counter, and the modulus operator, such as; <?php $i=1; $last_item = null; foreach($array As $item){ if($i % 2 == 1){ echo('<a href="'.$last_item.'">'.$item.'</a>'); } $last_item = $item; $i++; } ?> -cb- Link to comment https://forums.phpfreaks.com/topic/209160-how-to-foreach-this-array/#findComment-1092354 Share on other sites More sharing options...
Alex Posted July 28, 2010 Share Posted July 28, 2010 You could also use a for loop like this: for($i = 0, $n = sizeof($arr);$i < $n;++$i) { echo '<a href="' . $arr[$i] . '">' . $arr[++$i] . '</a>' ; } Link to comment https://forums.phpfreaks.com/topic/209160-how-to-foreach-this-array/#findComment-1092355 Share on other sites More sharing options...
newbtophp Posted July 28, 2010 Author Share Posted July 28, 2010 Thanks ChemicalBliss and Alex. And for your interest, I was'nt generating the array, it was generated by func_get_args() /Solved Link to comment https://forums.phpfreaks.com/topic/209160-how-to-foreach-this-array/#findComment-1092359 Share on other sites More sharing options...
cemrotterdam Posted July 28, 2010 Share Posted July 28, 2010 Hi, You can use this codes <?php $x=array("index.php","page.php?id=23"); foreach ($x as $value1) { echo $value1 . "<br />"; //echo '<a href="">$value1</a>'; } ?> <?php $x=array("Home","Page"); foreach ($x as $value2) { echo $value2 . "<br />"; //echo '<a href="">$value2</a>'; } ?> I hope this works Greetings Link to comment https://forums.phpfreaks.com/topic/209160-how-to-foreach-this-array/#findComment-1092380 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.