Implode a column of values from a two dimensional array [duplicate]
Asked Answered
K

3

12

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 ', '
Kaine answered 31/1, 2011 at 18:22 Comment(1)
@Rafe Kettler: Yeah but it only works on single-dimensional arrays.Sansen
H
28

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 :)

Hardan answered 31/1, 2011 at 18:25 Comment(4)
I am getting array_pop() expects parameter 1 to be array, string givenBackwash
@DhanuK I don't see the code, but I would make a wild guess that you have an array with items not an array of arrays with items.Hardan
I am getting array_pop() expects parameter 1 to be arrayEleen
@Eleen you're probably not passing array as first parameter. I can't see your code, but check whether array_pop($yourVariableWhichIsSupposedToBeAnArray) works.Hardan
M
24

In PHP 5 >= 5.5.0

implode(', ', array_column($array, 'name'))
Marlonmarlow answered 10/4, 2015 at 9:39 Comment(0)
S
18

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));
Sansen answered 31/1, 2011 at 18:24 Comment(4)
Yeah, but PHP does it much faster. Thanks.Kaine
This would be preferably to using array_pop(). If your 2nd tier array is given additional keys, it is not guaranteed the "name" key will be the first in the stack. Defensive programming FTW.Mucker
On another note, if you are skeptical about creating a new function in the namespace, then either use closures or create_function. echo implode(', ', array_map(create_function('$a', 'return $a["name"];'), $array));Mucker
You've got a very good point regarding your second comment, but in this case singles solution will do just fine. And yes, i am a bit skeptical about creating functions for this kind of usage. You see, i'm in the middle of learning OOP, so i'm kind of confused about when and where to use "normal" functions. Your last comment solved that though. I wish i could accept two posts.Kaine

© 2022 - 2024 — McMap. All rights reserved.