PHP: Implode a Multi-dimensional Array

PHP’s implode is a pretty handy function to flatten any array into a single string value, using any piece of ‘glue’ (basically a substring) that you specifiy to put everything together.

So in other words, if we had an array containing the string values of cat, dog and chicken and then ran the implode function against them using the character ‘|’ as glue, we would end up with a single string value reading cat | dog | chicken.

Of course, extending this function to handle multi-dimensional arrays (or matrices if you prefer) is a pretty simple matter of quickly whipping up a recursive version and so without any further waffling from my side, here’s the code:

//flattens a multi-dimensional array (recursive implode)
//-----------------------------------------------------------
function r_implode( $glue, $pieces )
{
        foreach( $pieces as $r_pieces )
        {
                if( is_array( $r_pieces ) )
                {
                        $retVal[] = r_implode( $glue, $r_pieces );
                }
                else       
                {
                        $retVal[] = $r_pieces;
                }
        }
        return implode( $glue, $retVal );
} 
//-----------------------------------------------------------

Usage is pretty simple. Call the r_implode function as normal, passing to it the ‘glue’ string you wish to employ as well as the array against which to run it.

Have fun.

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , , , , , , , . Bookmark the permalink.
    blog comments powered by Disqus