PHP: How to Convert Array to String using implode()
By Parth Patel on Nov 18, 2020
Previously, we discussed how to convert string to array in php using 3 different methods. Today, we will learn how we can convert PHP arrays to strings.
Convert PHP Array to String using implode()
PHP comes with its native function to convert Array to string called implode().
The implode() function has two implementation:
The implode() function that accepts two arguments - String used to join array elements & Array itself
Example: Here we will join array elements using ", " to store it as comma separated values.
$arr = ['Thor','Captain America','Iron Man']; echo implode(', ',$arr); // "Thor, Captain America, Iron Man"
The implode() function that accepts only one argument - Array to be converted
Here, the string to be used to join elements defaults to empty string. Therefore, elements are joined together without any separator.
Example:
$arr = ['H','e','l','l','o']; echo implode($arr); // "Hello"
Note: If the PHP array contains non-string items, implode function will first convert it to string and use it in the joined string. Boolean values are representated as → true = 1, false = 0.
Convert PHP Associative Array to String using implode()
The implode() function can not only join arrays with integer index but with string index as well, which we call it as associative arrays.
There are two approaches to this:
1) Combine only values to string
This is very simple since implode() function only considers array item's value and not index. So, you can use implode() function directly like below:
$users = [
'user1' => 'user1@example.com',
'user2' => 'user2@example.com'
];
echo implode(', ',$users);
// "user1@example.com, user2@example.com"
2) Combine both Index and value to string
If you want to use both values and index while joining array to string, then it gets complex. There are many ways to achieve this. Also, it depends how you want to represent the index and values in string. The implode() doesn't have any native functionality to handle such situations therefore, we will use multiple PHP functions including implode() function to achieve the same.
Example: Using the same associative array shown above, we will use both index and value i.e username and email address and combine it as follow:
$users = [
'user1' => 'user1@example.com',
'user2' => 'user2@example.com'
];
$flattened = $array;
array_walk($flattened, function(&$value, $key) {
$value = "{$key}:{$value}";
});
echo implode(', ', $flattened);
// "user1:user1@example.com, user2:user2@example.com"
In above example, we are combining username and email via color (:) by applying our custom function to each element in array using array_walk and then using implode(), we convert it to string.
Convert PHP Array of Arrays to String using implode()
Array can not only hold primary data types but Arrays and objects as well. If your Array holds arrays then combining all items at sub-level can get tricky.
The implode() cannot combine items at sub-level, therefore it doesn't work with array of arrays directly.
Example: Notice here , implode() method only considers top-level items and while converting items to string, it returns "Array" as string.
$users = [
'users' => ['user1@example.com','user2@example.com'],
'admins' => ['admin1@example.com', 'admin2@example.com']
];
echo implode(', ',$users);
// Array, Array
So, what should we do?
There are different ways to achieve this and depends on what kind the array is. For our simple example above, easiest approach would be to loop-through the array to retrive each sub-array and join them.
Example:
$users = [
'users' => ['user1@example.com','user2@example.com'],
'admins' => ['admin1@example.com', 'admin2@example.com']
];
// function to convert array of arrays to string
function implodeArrayofArrays($array, $glue = ', ') {
$output = '';
foreach ($array as $subarray) {
$output .= implode($separator, $subarray);
}
return $output;
}
echo implodeArrayofArrays($users);
// "user1@example.com, user2@example.com, admin1@example.com, admin2@example.com"
But, if your arrays has more levels - multidimensional array then you will have to check whether the item is of Array type or not. If it is then loop through that array as well.
Convert PHP Array to String using json_encode() and serialize()
There are other ways to convert PHP arrays to string as well. We will explore two methods to convert array to string in PHP. These functions even though returns string, have different purpose.
1) json_encode()
This function is very useful to not only convert PHP array to strings but pass it to javascript as well. You cannot pass PHP arrays to JavaScript directly, so you can convert it to JSON string using json_encode() and use it in JavaScript efficiently.
$arr = ['Thor','Captain America','Iron Man'];
echo json_encode($arr);
// "['Thor','Captain America','Iron Man']"
2) serialize()
This function is helpful when you want to convert PHP array into storable representation. Like, when you want to store PHP array in a memory buffer, this function can be helpful.
$arr = ['Thor','Captain America','Iron Man'];
echo serialize($arr);
// a:3:{i:0;s:4:"Thor";i:1;s:15:"Captain America";i:2;s:8:"Iron Man";}
That's all for today! Keep Learning
Adios.