PHP implode() Function
PHP implode() Syntax
implode(string $separator, array $array): string
PHP implode() Basic examples
$parts = ["apple", "banana", "orange"];
echo implode(", ", $parts);
apple, banana, orange
Joins array elements into a comma-separated string.
$parts = ["2024", "01", "31"];
echo implode("-", $parts);
2024-01-31
Formats date parts into a readable string.
$parts = [];
echo implode(",", $parts);
Imploding an empty array returns an empty string.
PHP implode() Real-world usage
$tags = ["php", "twig", "symfony"];
echo implode(", ", $tags);
php, twig, symfony
Creates a human-readable list from an array.
$pathParts = ["var", "www", "html"];
echo implode("/", $pathParts);
var/www/html
Builds a filesystem path from directory segments.
PHP implode() Edge cases
$values = [1, true, null, "test"];
echo implode(",", $values);
1,1,,test
Non-string values are cast to strings when imploded.
$values = [["a"], ["b"]];
echo implode(",", $values);
Array,Array
Nested arrays are converted to the string \"Array\".
PHP implode() Common mistakes
Passing the parameters in the wrong order
implode() accepts both orders, but consistency matters.
echo implode($parts, ",");
echo implode(",", $parts);
Always use implode(separator, array) for clarity.
Imploding unsanitized user input
Array values should be validated or escaped before output.
echo implode(",", $_GET['tags']);
echo implode(",", array_map('htmlspecialchars', $_GET['tags']));
Always sanitize user-provided data.
PHP implode() Frequently Asked Questions
What does implode() do in PHP?
implode() joins array elements into a single string using a specified separator.
What is the syntax of implode()?
implode(string $separator, array $array): string
What happens if the array is empty?
implode() returns an empty string if the array is empty.
Can implode() work without a separator?
Yes, if no separator is provided, implode() joins elements without any delimiter.
What is the difference between implode() and join()?
There is no difference, join() is an alias of implode().
Does implode() modify the original array?
No, implode() returns a new string and does not modify the original array.
Can implode() handle nested arrays?
No, implode() works only with one-dimensional arrays.
Is implode() case-sensitive?
implode() does not perform comparisons, so case sensitivity is not relevant.
What happens if array contains non-string values?
Non-string values are automatically converted to strings when using implode().
What is a real-world use case of implode()?
implode() is commonly used to build CSV strings, generate query parameters, or format output.
How to combine implode() with explode()?
explode() splits a string into an array, while implode() joins it back into a string.
Can implode() use different separators?
Yes, you can use any string as a separator such as commas, spaces, or custom characters.