Skip to content

Instantly share code, notes, and snippets.

@MarxBro
Forked from jimmygle/PHP-Recursive-Implosion.php
Created November 22, 2016 01:39
Show Gist options
  • Save MarxBro/f08a8768f06f57cff4e627cb4a9a4630 to your computer and use it in GitHub Desktop.
Save MarxBro/f08a8768f06f57cff4e627cb4a9a4630 to your computer and use it in GitHub Desktop.
PHP function to recursively implode multi-dimensional arrays.
<?php
/**
* Recursively implodes an array with optional key inclusion
*
* Example of $include_keys output: key, value, key, value, key, value
*
* @access public
* @param array $array multi-dimensional array to recursively implode
* @param string $glue value that glues elements together
* @param bool $include_keys include keys before their values
* @param bool $trim_all trim ALL whitespace from string
* @return string imploded array
*/
function recursive_implode(array $array, $glue = ',', $include_keys = false, $trim_all = true)
{
$glued_string = '';
// Recursively iterates array and adds key/value to glued string
array_walk_recursive($array, function($value, $key) use ($glue, $include_keys, &$glued_string)
{
$include_keys and $glued_string .= $key.$glue;
$glued_string .= $value.$glue;
});
// Removes last $glue from string
strlen($glue) > 0 and $glued_string = substr($glued_string, 0, -strlen($glue));
// Trim ALL whitespace
$trim_all and $glued_string = preg_replace("/(\s)/ixsm", '', $glued_string);
return (string) $glued_string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment