Join Words
Write a PHP function that joins an array of words into a single string using implode(). The function should separate words with a space by default, but accept a custom separator as an optional parameter.
The implode() function in PHP joins array elements with a specified separator string. It is the counterpart to explode() which splits a string into an array. The function handles empty arrays by returning an empty string.
Edge cases include empty arrays (return ''), single-element arrays (return the element without separator), arrays with numbers (they are cast to strings), and custom separators like commas or hyphens.
PHP's implode() is the counterpart to explode(), forming a complete string from array elements. It is commonly used in template rendering, URL building, and CSV generation. The optional separator parameter makes it flexible for different formatting needs.
Joining array elements into strings is essential for display formatting, data serialization, and template rendering. PHP's implode() efficiently concatenates elements with a separator in a single function call, avoiding manual loops.
Default parameter values in PHP allow the function to work with a common case (space separator) while remaining customizable. This pattern of optional parameters with sensible defaults is widely used in PHP function design.
Example Input & Output
Algorithm Flow

Solution Approach
Use implode($separator, $words) where $separator defaults to ' '. The implode function concatenates array elements with the separator between them. For an empty array, implode returns an empty string.
For a manual implementation without implode, use a loop: start with the first element, then for each subsequent element, append the separator plus the element. This gives you control over formatting.
Edge cases include empty arrays (return ''), single-element arrays (return that element), and numeric arrays (PHP automatically converts to strings).
The time complexity is O(n). Space complexity is O(n) for the result string.
Best Answers
<?php
function joinWords($words, $separator = ' ') {
return implode($separator, $words);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
