Implode a column of values from a two dimensional array

43.5k Views Asked by At

I've got an array like this:

Array
(
    [0] => Array
        (
            [name] => Something
        )

    [1] => Array
        (
            [name] => Something else
        )

    [2] => Array
        (
            [name] => Something else....
        )
)

Is there a simple way of imploding the values into a string, like this:

echo implode(', ', $array[index]['name']) // result: Something, Something else, Something else...

without using a loop to concate the values, like this:

foreach ($array as  $key => $val) {
    $string .= ', ' . $val;
}
$string = substr($string, 0, -2); // Needed to cut of the last ', '
3

There are 3 best solutions below

4
On BEST ANSWER

Simplest way, when you have only one item in inner arrays:

$values = array_map('array_pop', $array);
$imploded = implode(',', $values);

EDIT: It's for version before 5.5.0. If you're above that, see better answer below :)

4
On

You can use a common array_map() trick to "flatten" the multidimensional array then implode() the "flattened" result, but internally PHP still loops through your array when you call array_map().

function get_name($i) {
    return $i['name'];
}

echo implode(', ', array_map('get_name', $array));
0
On

In PHP 5 >= 5.5.0

implode(', ', array_column($array, 'name'))