PHP Tutorials
Oct 5, 2022

PHP Implode() Function - Join Array Elements Into A String

Take a look at how we can use the implode() function to join array elements together into a string

Matt Payne
Matt Payne

We're going to take a look at how we can use the implode() function to join array elements together into a single string. We'll walk through various implementations and examples that show how this function can be used in a production setting.

PHP Implode() Function Introduction & Syntax

The PHP implode() function is used to merge elements from an array into a single string with a character of our choosing as the delimiter. Often times implode() is used to prepare data for database insertion given most database systems do not allow for arrays to be inserted. The implode function is also useful for debugging purposes by allowing us to print out each element in an array in a human-readable manner. The second use case is when we are concatenating multiple string values into a larger string. 

Parameters For Implode() Function

The first parameter is the delimiter that we use to split up our string and is a mandatory parameter. The second parameter is the source array which is mandatory in order for us to concatenate any all array element values. 

Delimiter 

We pass in a separator string to split up our combined string by. This can be any strings of characters of our choosing. In the example below we use the string ‘, ’. The space after the comma is important to add as the function will replace spaces with nothing essentially creating additional delimiters. 

SourceArray

This is the source array we want to convert into a combined string using the given delimiter. If you provide an empty array the result will be an empty string. Elements will be combined in the same order as the array.

Return Values For Implode() Function

The return value of the function is a combined string of each element in the source array merged together. The function only returns strings, therefore if the source array contains values that are not strings the function will cast those types to strings before concatenation. If our source array is empty or contains only a single value, the return value will be the same as the first value in the $sourceArray parameter.

Errors and Exceptions for Implode() Function

If the function fails to perform as expected it will return NULL. 

Typically errors for this function are due to an invalid data type given as a parameter. For example, the following code returns an empty string because our delimiter is an integer value. 


$implode = implode(500, array(1,2,3,4,5));
var_dump($implode);

Our output in this case would be a boolean false

bool(false)

You may also encounter an issue where you may be trying to use implode() on an object data type.


$obj = new stdClass;
$obj->firstName = 'Adam';
$obj->lastName = 'Wilk';
print implode(' ', (array)$obj);

In the example above when using the implode function directly on the object data type it will return the following error message: 

Catchable fatal error: “Object of class stdClass could not be converted to string”

In order to use the implode function on an object you must first cast it to an array using the (array) syntax as seen in the second parameter of our print statement. If you do not do this, you will be presented with the fatal error message shown above. 

PHP Implode() Examples 

Let’s look at a number of examples of how we can use implode() to join array elements together into a string variable. 

Simple Convert PHP Array to String Representation Examples 

This example below uses the implode() function to join php array elements with a space as a separator between each element in the array. 


$arr = array('PHP', 'coding', 'website');
$space_separated = implode(" ", $arr);
echo $space_separated; // PHP coding website

 

You'll notice that our outputted string has a space between each of the array elements. We can also use an empty string as a separator which would result in no space between each array element. 

Note: If your array has null values they are imploded as well. You can use the array_filter() PHP function to remove any null values. 

PHP Implode() with Associative Array


$assoc_array = array('firstName' => 'Matt', 'lastName' => 'Smith');
$comma_separated = implode(", ", $assoc_array);
echo $comma_separated; // firstName=Matt, lastName=Smith 

In this example, we created a PHP associative array with two elements and imploded them together using a separator of a comma and space. You can see that our outputted string contains the array keys and values with the separator in between. 

This can be useful for creating CSV or TSV files from array data.

PHP Implode() Multidimensional Array

In this final simple example, we create a multidimensional php array and use implode() to flatten the array structure into a single string with each element separated by a comma and space. You can see that the original array structure is lost when imploding a multidimensional array and only the raw individual elements are returned in our final string.


$multi_array = array( array('PHP', 'coding'), array('website', 'development') );
$flat = implode(", ", $multi_array);echo 
$flat; // PHP, coding, website, development

Deeper Examples Of PHP implode() 

Let’s look at some powerful and efficient ways to use the implode() function. 

Search An Array And Implode The Results 

In this first example, we’re going to look for a specific value in an array and then combine the results into a string. We’ll use the in_array() and implode() functions for this task. 

Our $subscribers array contains E-mail address strings. We’re going to use in_array() to check whether a specific E-mail address string is in that array. The in_array() function returns either true or false which we can use in an if statement.  


$subscribers = ['name@example.com','test@example.com','info@example.com','jobs@example.com'];
$needle = 'info@example.com';
if (in_array($needle, $subscribers)){
	$key = array_search($needle, $subscribers);
  echo $subscribers[$key];
}

We can see that the string we were looking for is in the php array and we output it to the screen. If we wanted to implode all the results that are in the array we can do the following: 

$subscribers = ['name@example.com','test@example.com','info@example.com','jobs@example.com']; $needle = 'info@example.com'; if(in_array($needle, $subscribers)){ $key = array_search($needle, $subscribers); $implode = implode(',', $subscribers); echo $implode; } 


$subscribers = ['name@example.com','test@example.com','info@example.com','jobs@example.com'];
$needle = 'info@example.com';
if (in_array($needle, $subscribers)){
	$key = array_search($needle, $subscribers);
  echo $subscribers[$key];

Implode An Array Based On Key Values 

In this second example, we’re going to look at how we can combine or ‘implode’ an array based on specific key values. We’ll use the array_column() and implode() functions for this task. Our $studentGrades array contains grade information for different students. We’re going to look at how we can implode the E-mail address strings for each student. 


$studentGrades = [ ['name'=>'John Doe','email'=>'john@example.com','grade'=>'A'], ['name'=>'Jane Smith','email'=>'jane@example.com','grade'=>'B'], ['name'=>'Jim Moore','email'=>'jim@example.com','grade'=>'C'] ];
$studentEmail = array_column($studentGrades, 'email', 'name');
$studentEmailImplode = implode(',', $studentEmail);
echo $studentEmailImplode;

We use the array_column() function to grab all the E-mail address values from our $studentGrades array. Then we use implode() and combine those values into a comma-separated string.

how long does php implode take? 

Here’s a quick script that allows you to test the runtime of your implode() function. The speed relies heavily on the size of your PHP array. 


$time_start = microtime(true);
/* Your code to test goes here */
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time microseconds\n";

Implode() Summary- Convert Array to String

The Implode() function is one of the best ways to convert PHP arrays of different types and multiple, one, or no elements to a string. The function takes an array as the first parameter and a string to serve as the glue that concatenates the array’s values together. This is a great way to prepare data for insertion into a database or to convert an array of data into a string for output.

php logo

Instant Access To PHP Case Studies

Read real use cases and whitepapers using PHP