/** * Convert a traversable or other value into an array or leave it as is if it already is an array. * * Additional argument can be set to true to force conversion of empty values * into empty arrays. By default any not-array and not-traversable value will * be casted as array. * * @param mixed $var the value * @param bool $empty_value_to_empty_array force conversion of empty values * into empty arrays (optional, default is false) * @return array the value as is if it is an array, or the value * converted to an array */ function to_array($var, bool $empty_value_to_empty_array = false) : array { if ($empty_value_to_empty_array && empty($var)) { return []; } if (is_array($var)) { return $var; } if (is_traversable($var)) { return traversable_map(pass_through, $var); } return (array) $var; }
/** * Flatten an array or a traversable. * * @param array|\Traversable $traversable the traversable to flatten * @param bool $preserve_keys preserve original keys of all arrays (default is false) * @return array flat array */ function traversable_flatten($traversable, bool $preserve_keys = false) : array { $flat = []; if ($preserve_keys) { foreach (to_traversable($traversable) as $key => $value) { if (is_traversable($value)) { $flat = array_merge($flat, traversable_flatten($value, true)); } else { $flat[$key] = $value; } } } else { foreach (to_traversable($traversable) as $value) { if (is_traversable($value)) { foreach (traversable_flatten($value, false) as $subvalue) { $flat[] = $subvalue; } } else { $flat[] = $value; } } } return $flat; }