PHP Looping through array recursive

Posted on

PHP Looping through array recursive – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and symfony . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about PHP Looping through array recursive.

I want to loop through an array in PHP. The loop must be recursive, because I don’t now how many arrays-in-arrays there are. It is for reading translations in Symfony2.

The output format is:

a.d.e
a.f.g
b.h.i
c.j.k.l.m
c.n.o

with example array:

$array = array(
    'a' => array('d' => 'e', 'f' => 'g'),
    'b' => array('h' => 'i'),
    'c' => array(
        'j' => array(
            'k' => array(
                'l' => 'm')),
        'n' => 'o'));

I have tried the following, but this is not a final solution, but the recursion is working:

function displayArrayRecursively($array)
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {
            echo $key . '<br>';
            displayArrayRecursively($value);
        } else {

            echo $key . '<br>' . $value . '<br>';       
        }
    }
}

Thanks in advance!

Solution :

I guess your function just output

a
d
e
...

Something like this should work :

displayArrayRecursively($array, null);

function displayArrayRecursively($array, $keysString = '')
{
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            displayArrayRecursively($value, $keysString . $key . '.');
        }
    } else {
        echo $keysString . $array . '<br/> ';
    }
}

It should be pretty close to what you need.

This function does what you want:

function displayArrayRecursively($array, $tree = array()) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            displayArrayRecursively($value, array_merge($tree, array($key)));
        } else {
            print implode('.', array_merge($tree, array($key, $value)));
            print "n<br />";
        }
    }
}

Output:

a.d.e
a.f.g
b.h.i
c.j.k.l.m
c.n.o

Function you want

function displayArrayRecursively($array, $parent = '')
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {
            if(count($value) == 1 && !empty($parent))
                $key = $parent . $key;
            displayArrayRecursively($value, $key);
        } else {
            echo $parent;
            echo $key . $value . '<br>';       
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *