Last active
March 22, 2016 19:19
-
-
Save bizley/23b0b29540f284440313 to your computer and use it in GitHub Desktop.
Multidimensional array implode (PHP >= 5.4)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great!
throw new \yii\base\InvalidParamException
may better