Jump to content

How to foreach this array?


newbtophp

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

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.