0

I have some WordPress custom fields data that I am looping through and creating a comma separated string. The (small) issue is that I get a warning if I don't set the property as empty / null etc before looping.

I guess you can't concatenate a string if it doesn't yet exist. Although I get the warning, the foreach does what I need an there are no errors.

To stop the warning I have set the property as an empty string to start:

$memlog->postnominals = "";
foreach (get_field('post_nominals', $post->id) as $postnominal) {
    $memlog->postnominals .= $postnominal->post_title . ", ";
}

Although not a big issue, I would rather know if there is a way I can do this without setting an empty string?

Lovelock
  • 7,689
  • 19
  • 86
  • 186

2 Answers2

2

Don't use concatenation to begin with, join an array, that way you also don't have to strip off the last , afterwards:

$memlog->postnominals = join(', ', array_column(get_field(...), 'post_title'));

array_column only works with objects in PHP 7+, for older versions use a map:

$memlog->postnominals = join(', ', array_map(
    function ($p) { return $p->post_title; }, 
    get_field(...)
));
deceze
  • 510,633
  • 85
  • 743
  • 889
0

Please use array then implode that data from array to form comma separated string.

Example:

        $aa = array(1 => 'a', 2 => 'b', 3 => 'c');
        foreach ($aa as $k => $v) {
            $b[] = $v;
        }
        print_r(implode(',', $b));
Vijay Maurya
  • 99
  • 1
  • 6
  • 2
    Just to point it out: in this particular sample the `foreach` is completely superfluous. You could `implode` `$aa` directly. – deceze Sep 07 '17 at 09:56
  • Yeah, actually you are right. But if you want to perform some extra task then you can this loop otherwise just use implode. – Vijay Maurya Sep 07 '17 at 10:26