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> Quote 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- Quote 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>' ; } Quote 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 Quote 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 Quote 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
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.