PHP: How to Create a Single String of Array Keys using Implode CodeUnit 09 NOV 2011

PHP’s implode function is extremely useful for flattening a one dimensional array into a string. This time around, we want to create a flat string of an array’s keys, ignoring the actual values for a change.

To achieve this is actually very simple – it’s just a matter of combining the stock standard array_keys() and implode() functions together!

So given an array that looks like this:

$myarray = array('green'=>'leaf','blue'=>'sky','red'=>'apple');

We can get a flattened string reading green||blue||red by doing the following:

echo implode('||',array_keys($myarray));

Simple. The array_keys function first returns an array containing the keys of our aforementioned array, before the implode function flattens it using || as a delimiter.


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.