0

I have an array like this:

$my_arr = Array (
  [0] => WP_Term Object (
    [term_id] => 15
    [name] => Foo
    [slug] => foo
    [term_group] => 0
    [term_taxonomy_id] => 15
    [taxonomy] => product_cat
    [description] => 
    [parent] => 0
    [count] => 1
    [filter] => raw
  ),
  [1] => WP_Term Object (
    [term_id] => 16
    [name] => Bar
    [slug] => bar
    [term_group] => 0
    [term_taxonomy_id] => 16
    [taxonomy] => product_cat
    [description] => 
    [parent] => 0
    [count] => 1
    [filter] => raw
  ),
  [2] => WP_Term Object (
    [term_id] => 17
    [name] => Foobar
    [slug] => foobar
    [term_group] => 0
    [term_taxonomy_id] => 17
    [taxonomy] => product_cat
    [description] => 
    [parent] => 0
    [count] => 1
    [filter] => raw
  ),
)

And I'm trying to output:

Foo, Bar, Foobar

A way to get this is to loop through it adding it to an array:

$final_value = [];
foreach( $my_arr as $a ){
  $final_value[] = $a->name;
}
echo implode( $final_value, ', ' );

But I catch myself doing this A LOT.

So I was wondering if there was a way that's briefer (it's especially the foreach that annoys my eye)?

Perhaps there's something that is faster as well?

Zeth
  • 2,273
  • 4
  • 43
  • 91

1 Answers1

2

Yes, you can use array_column https://www.php.net/manual/en/function.array-column.php

Oleg Andreyev
  • 647
  • 5
  • 20