Home  >  Article  >  Backend Development  >  How to Access a Nested Array at a Specific Index Using foreach in PHP?

How to Access a Nested Array at a Specific Index Using foreach in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-17 22:07:02576browse

How to Access a Nested Array at a Specific Index Using foreach in PHP?

PHP foreach with Nested Array

Question: How to access a specific nested array using a foreach loop in PHP?

Consider the following nested array:

<code class="php">array(
    [0] => array(
        [0] => one
        [1] => array(
            [0] => 1
            [1] => 2
            [2] => 3
            )
        )

    [1] => array(
        [0] => two
        [1] => array(
            [0] => 4
            [1] => 5
            [2] => 6
            )
        )

    [2] => array(
        [0] => three
        [1] => array(
            [0] => 7
            [1] => 8
            [2] => 9
            )
        )
    )
);</code>

The goal is to iterate through the values of the nested array at key 1, without using a variable comparison.

Answer: There are two approaches to achieve this:

1. Nested Loops (Fixed Depth):

This method is suitable if the depth of the nested arrays is known in advance.

<code class="php">foreach ($tmpArray as $innerArray) {
    if (is_array($innerArray)) {
        foreach ($innerArray as $value) {
            echo $value;
        }
    } else {
        echo $innerArray;
    }
}</code>

2. Recursive Function (Unknown Depth):

This approach is used when the depth of the nested arrays is unknown. It involves a recursive function that traverses the array:

<code class="php">function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                displayArrayRecursively($value, $indent . '--');
            } else {
                echo "$indent $value \n";
            }
        }
    }
}

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

displayArrayRecursively($tmpArray);</code>

Specific Case:

To access only the nested array with values for the third level (key 2), use the following code:

<code class="php">foreach ($tmpArray as $inner) {
    if (is_array($inner)) {
        foreach ($inner[1] as $value) {
            echo "$value \n";
        }
    }
}</code>

The above is the detailed content of How to Access a Nested Array at a Specific Index Using foreach in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn