Loop through a two-dimensional array

22,058

Solution 1

In order to echo out the bits you have to select their index in each array -

foreach($array as $arr){
    echo '<a href="'.$arr[0].'">'.$arr[1].'</a>';
}

Here is an example.

Solution 2

Use nested foreach() because it is 2D array. Example here

foreach($array as $key=>$val){ 
    // Here $val is also array like ["Hello World 1 A","Hello World 1 B"], and so on
    // And $key is index of $array array (ie,. 0, 1, ....)
    foreach($val as $k=>$v){ 
        // $v is string. "Hello World 1 A", "Hello World 1 B", ......
        // And $k is $val array index (0, 1, ....)
        echo $v . '<br />';
    }
}

In first foreach() $val is also an array. So a nested foreach() is used. In second foreach() $v is string.

Updated according to your demand

foreach($array as $val){
    echo '<a href="'.$val[0].'">'.$val[1].'</a>';
}

Solution 3

The easiest way to loop through it is:

foreach ($array as $arr) {
    foreach ($arr as $index=>$value) {
        echo $value;
    }
}

EDIT:

If you know that your array will have always only two indexes then you can try this:

foreach ($array as $arr) {
    echo "<a href='$arr[0]'>$arr[1]</a>";
}

Solution 4

First modify your variable like this:

$array = array(
          array("url"=>"http://google.com",
                "name"=>"Google"
          ),
          array("url"=>"http://yahoo.com",
                "name"=>"Yahoo"
          ));

then you can loop like this:

foreach ($array as $value)
{ 
   echo '<a href='.$value["url"].'>'.$value["name"].'</a>'
}

Solution 5

The way to loop through is,

foreach($array as $arr)
foreach($arr as $string) {
        //perform any action using $string
}

Use the first foreach loop without { } for the simplest use.

That can be the most simple method to use a nested array as per your request.

For your edited question.

Wrong declaration of array for using key.

$array = array( 
    "http://google.com" => "Google",
    "http://yahoo.com" => "Yahoo" );

And then, use the following.

foreach ($array as $key => $value)
    echo "<a href='{$key}'>{$value}</a>";

This doesn't slow down your server's performance.

Share:
22,058
Henrik Petterson
Author by

Henrik Petterson

Immigrant.

Updated on May 14, 2021

Comments

  • Henrik Petterson
    Henrik Petterson almost 3 years

    I have an array that looks like this:

    $array = array(
        array(
            "http://google.com",
            "Google"
        ),
    
        array(
            "http://yahoo.com",
            "Yahoo"
        )
    );
    

    What is the simplest way to loop through it. Something like:

    foreach ($array as $arr) {
        // help
    }
    

    EDIT: How do I target keys, for example, I want to do:

    foreach ($array as $arr) {
        echo '<a href" $key1 ">';
        echo ' $key2 </a>';
    }