PHP: Implode a Multi-dimensional Array CodeUnit 09 APR 2010

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.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • ori shmolovsky

    Thanks this is an optimal solution.

  • Recursive Solution… Thanks for the code

  • system_se7en

    Thank you, This got me past a huge road block. Much appreciated!

  • Jim Evans

    Thank for this, neat little function. One issue – it generates a notice that $retVal hasn’t been defined. It needs the following change:

    function r_implode( $glue, $pieces ){

            $retVal = array(); // This defines the array so it doesn’t generate a notice

    foreach( $pieces as $r_pieces ) {

        if( is_array( $r_pieces ) )    {

          $retVal[] = r_implode( $glue, $r_pieces );

        }
        else
        {

          $retVal[] = $r_pieces;

        }

      }

      return implode( $glue, $retVal );

    }

  • Why to use array_walk_recursive

    function arrayToString($array,$multi=FALSE,$delimeter=”,”){
    $_retArr=”;
    if(!is_array($array) || count($array)<1)
    return $_retArr;
    array_walk_recursive($array,function($value, $key) use(&$_retArr,$delimeter)
    {
    $_retArr.= $value.$delimeter;
    });
    return trim($_retArr,$delimeter);
    }