3

I have this kind of array in my $tag variable.

Array
(
    [0] => Array
        (
            [tag_name] => tag-1
        )
    [1] => Array
        (
            [tag_name] => tag-2
        )
    [2] => Array
        (
            [tag_name] => tag-3
        )
)

What I'm trying to do is get all the tag names and implode them with a coma then make it a value for a text input field.

I've tried for and foreach loops so many different ways but with not much success. I'm using CodeIgniter if that helps.

Machavity
  • 30,841
  • 27
  • 92
  • 100
mzcoxfde
  • 235
  • 2
  • 13

4 Answers4

3

You can use array_column followed by join or implode

Try this :

$string = join(',', array_column($array, 'tag_name'));

Explanation:

array_column returns the values from a single column from the input array

For your array, array_column($array 'tag_name') returns an array containing values of index tag_name, i.e returned array would be :

Array
(
    [0] => tag-1
    [1] => tag-2
    [2] => tag-3
)

Joining with join or implode , you get your desired string,

//$string = "tag-1,tag-2,tag-3"
Robin Panta
  • 224
  • 3
  • 11
2

A simple and obvious solution might be:

$res = "";
for ($i = 0; $i < count($tag); $i++) {
    $res .= $tag[$i]["tag_name"] . ",";
}
$res = trim($res, ","); //Removing the extra commas
echo $res;

You basically iterate through the array, and every element you iterate through, you add it's tag_name to a $res string.

Yotam Salmon
  • 2,400
  • 22
  • 36
2

Use array_column

$tag = implode(', ', array_column($array, 'tag_name'));

Using array_map:

$tag = implode(', ', array_map(function ($tag) {
          return $tag['tag_name'];
        }, $array));
jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39
1

Simple one liner !!

$array = [
    [
        "tag_name" => 'tag-1'
    ],
    [
        "tag_name" => 'tag-2'
    ],
    [
        "tag_name" => 'tag-3'
    ],
];

implode(',', array_column($array, 'tag_name'));
Shirraz
  • 172
  • 1
  • 4
  • 10