Tag Archives: flatten

PHP: How to Create a Single String of Array Keys using Implode CodeUnit 09 NOV 2011

PHP’s implode function is extremely useful for flattening a one dimensional array into a string. This time around, we want to create a flat string of an array’s keys, ignoring the actual values for a change.

To achieve this is actually very simple – it’s just a matter of combining the stock standard array_keys() and implode() functions together!

So given an array that looks like this:

$myarray = array('green'=>'leaf','blue'=>'sky','red'=>'apple');

We can get a flattened string reading green||blue||red by doing the following:

echo implode('||',array_keys($myarray));

Simple. The array_keys function first returns an array containing the keys of our aforementioned array, before the implode function flattens it using || as a delimiter.


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 );
      			$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.