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:
-
Getting all the possible string permutations of an array can be pretty useful if you are trying to unlock something and this nifty little function does exac ...
-
It's sometimes pretty valuable to reuse array structures if you're kind of doing a task over and over again, and don't necessarily want to recreate the arra ...
-
My tried and trusted method for inserting graphs into PDFs is to use the nifty PHP FPDF library and insert an image into it via a Google Chart URL. In ot ...
-
Today's little PHP hint is a pretty simple one, but one worth tackling if you are looking for a quick and easy way to strip a particular string pattern off ...
-
While you will quickly learn that adding something to an array in PHP is ridiculously easy, finding a way to remove something turns out not to be quite so e ...