PHP implode function to convert associative or indexed array to string

PHP implode function is the reverse of explode function. It concatenates the associative or indexed array values to make strings. We'll learn how to apply the implode function to concatenate the values of associative arrays, indexed arrays, and multidimensional arrays.

See the syntax of implode() function.

 implode($delimiter, $array);
 OR
 implode($array, $delimiter);

$delimiter

It works as glue or binder of the values of array. The default values is empty string. You may use other types of delimiters such as comma, colon, space, etc.

$array

It is the array of strings that we want to concatenate.

You can use either order of the implode's arguments function. But we usually use the first one to keep resemblance with explode() function.

See the following examples of implode function to concatenate the values of indexed arrays to get a string.

php implode function for indexed arrays

Example:

If we only pass the array to implode function. It will return the string concatenated with the empty string (''). Because the default value of second argument is the empty string ('').

$arr = ["James","CS16M036","3.8"];

$str = implode($arr);

// JamesCS16M0363.8

Example:

In this case, we pass the first argument as glue to bind the array values.

$arr = ["James","CS16M036","3.8"];

$str = implode(":", $arr);

echo $str;
// James:CS16M036:3.8

php implode function for associative arrays

An associative array consists of array-value pairs i.e. every value is associated with one key.

$arr = array("name"=>"James", 
	     "Roll_No"=>"CS16M036", 
	     "CGPA"=>"3.8");

$str = implode(":", $arr);	

echo $str;
// James:CS16M036:3.8

You can see that only array values are concatenated and not the keys.

You should use array_keys function to get the array of keys out of the associative array. Then, you may implode the array of keys.

$arr = array("name"=>"James", 
	     "Roll_No"=>"CS16M036", 
	     "CGPA"=>"3.8");

$str = implode("-", array_keys($arr));	

echo $str;
// name-Roll_No-CGPA

php implode function for multidimensional arrays

We can print the multidimensional array values as a string. See the following examples of implode function to concatenate the values of multidimensional indexed arrays.

In two dimensional array, we just walk through each sub array. And then apply the implode function to each sub array.

Example:

We have an array of arrays and we want to implode the values of arrays. But how we'll walk through the multidimensional arrays. We have to traverse the array with a loop. Then, we'll apply the implode function to the internal arrays.

$arr = [["James","CS16M036","3.8"],["Sheraz","CS16M038","3.1"],["John","CS16M037","3.2"]];

$str = "";
for($i=0;$i<count($arr);$i++)
{
	$str .= implode(":",$arr[$i]).', ';
}

echo $str;

// James:CS16M036:3.8, Sheraz:CS16M038:3.1, John:CS16M037:3.2

PHP

How to split string into array in php


Was this article helpful?