Skip to content

Instantly share code, notes, and snippets.

@bizley
Last active March 22, 2016 19:19
Show Gist options
  • Save bizley/23b0b29540f284440313 to your computer and use it in GitHub Desktop.
Save bizley/23b0b29540f284440313 to your computer and use it in GitHub Desktop.
Multidimensional array implode (PHP >= 5.4)
/**
* Join array elements with a string.
* This method works with multidimensional arrays.
*
* @param string|array $glue the string for the array to be joined with or
* the array itself if $array is null
* @param array|null $array array to implode or null if array is provided as
* first parameter.
* @return string imploded array
* @throws \yii\base\InvalidParamException
*/
public static function implode($glue, $array = null)
{
if ($array === null) {
$array = $glue;
$glue = '';
}
if (!is_array($array)) {
throw new \yii\base\InvalidParamException('You must provide an array to implode.');
}
if (!is_string($glue)) {
throw new \yii\base\InvalidParamException('Parameter $glue must be a string.');
}
$flat = [];
array_walk_recursive($array, function ($element) use (&$flat) { $flat[] = $element; });
return implode($glue, $flat);
}
@zuoRambo
Copy link

zuoRambo commented Dec 7, 2015

great! throw new \yii\base\InvalidParamException may better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment