PHP Implode Array Key Value – Array Keys To String

Overview

In this tutorial, I will show how you can quickly and easily convert array keys, into a string. The method I use will convert array key values into an array without using foreach() function.

The idea of this code snippet will allow you to convert this:

<?php

$array = (
    'John' => 'John is a common name',
    'Mark' => 'Mark is eating a sandwich',
    'Sarah' => 'Sarah does not like Mondays',
);

Into this:

<?php

$names = 'John, Mark, Sarah';

PHP Implode Array Key Value – Array Keys To String

In PHP there is a great function for converting a PHP Array into a string (and visa versa) using the function implode(). These functions work well on the values of the array, however we are trying to convert he array keys. Luckily in PHP there is a function called array_keys() which will return a list of array keys from the array. Combining these two functions, we can easily convert the keys of an array into a string. Using php implode array key value will easily convert your array’s keys into a string.

Note that as this function converts the array keys into a string rather than the array values. As such, the array passed to the calling function should be an associative array.

The PHP Function

Here is the function used to convert the array keys into a string. If you want to learn how the function works, then view the explanation here.

<?php

// our simple yet effective implode array key function
function implodeArrayKeys($array) {
	return implode(", ",array_keys($array));
}

?>

How the above function works

This is the long winded version of this function explaining how the above implode array keys function works. You should use the above function as the function below is more for information purposes.

<?php

function implodeArrayKeys($array)
{
	// first we get the array keys using array_keys() PHP function
	$keys = array_keys($vars);

	// now join the keys into a string and separate using a comma
	$string = implode(", ",$keys);

	// and return the result
	return $string;
}

?>

And voila, it’s as easy as that.