Jump to content

Recommended Posts

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>

 

:confused:

Link to comment
https://forums.phpfreaks.com/topic/209160-how-to-foreach-this-array/
Share on other sites

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-

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.